Hex.cpp 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Array.h>
  7. #include <AK/ByteBuffer.h>
  8. #include <AK/Hex.h>
  9. #include <AK/String.h>
  10. #include <AK/StringBuilder.h>
  11. #include <AK/StringView.h>
  12. #include <AK/Types.h>
  13. #include <AK/Vector.h>
  14. namespace AK {
  15. Optional<ByteBuffer> decode_hex(StringView input)
  16. {
  17. if ((input.length() % 2) != 0)
  18. return {};
  19. auto output_result = ByteBuffer::create_zeroed(input.length() / 2);
  20. if (!output_result.has_value())
  21. return {};
  22. auto& output = output_result.value();
  23. for (size_t i = 0; i < input.length() / 2; ++i) {
  24. const auto c1 = decode_hex_digit(input[i * 2]);
  25. if (c1 >= 16)
  26. return {};
  27. const auto c2 = decode_hex_digit(input[i * 2 + 1]);
  28. if (c2 >= 16)
  29. return {};
  30. output[i] = (c1 << 4) + c2;
  31. }
  32. return output_result;
  33. }
  34. String encode_hex(const ReadonlyBytes input)
  35. {
  36. StringBuilder output(input.size() * 2);
  37. for (auto ch : input)
  38. output.appendff("{:02x}", ch);
  39. return output.build();
  40. }
  41. }