hex.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #pragma once
  2. #include <util/generic/string.h>
  3. #include <util/generic/yexception.h>
  4. #include <util/system/yassert.h>
  5. inline static char DigitToChar(unsigned char digit) {
  6. if (digit < 10) {
  7. return (char)digit + '0';
  8. }
  9. return (char)(digit - 10) + 'A';
  10. }
  11. extern const char* const Char2DigitTable;
  12. inline static int Char2Digit(char ch) {
  13. char result = Char2DigitTable[(unsigned char)ch];
  14. Y_ENSURE(result != '\xff', "invalid hex character " << (int)ch);
  15. return result;
  16. }
  17. //! Convert a hex string of exactly 2 chars to int
  18. /*! @example String2Byte("10") => 16 */
  19. inline static int String2Byte(const char* s) {
  20. return Char2Digit(*s) * 16 + Char2Digit(*(s + 1));
  21. }
  22. char* HexEncode(const void* in, size_t len, char* out);
  23. TString HexEncode(const void* in, size_t len);
  24. inline TString HexEncode(const TStringBuf h) {
  25. return HexEncode(h.data(), h.size());
  26. }
  27. //! Convert a hex string @c in of @c len chars (case-insensitive) to array of ints stored at @c ptr and return this array.
  28. /*! @note len must be even (len % 2 == 0), otherwise an exception will be thrown.
  29. * @return @c ptr, which is an array of chars, where each char holds the numeric value
  30. * equal to the corresponding 2 digits of the input stream.
  31. * @warning You must ensure that @c ptr has (len/2) allocated bytes, otherwise SIGSEGV will happen.
  32. *
  33. * @example HexDecode("beef", 4, ptr) => {190, 239}
  34. */
  35. void* HexDecode(const void* in, size_t len, void* ptr);
  36. //! Convert a hex string @c in of @c len chars (case-insensitive) to array of ints and return this array.
  37. /*! @note len must be even (len % 2 == 0), otherwise an exception will be thrown.
  38. * @return an array of chars, where each char holds the numeric value equal to the corresponding 2 digits
  39. * of the input stream.
  40. *
  41. * @example HexDecode("beef", 4) => {190, 239}
  42. */
  43. TString HexDecode(const void* in, size_t len);
  44. //! Convert an ASCII hex-string (case-insensitive) to the binary form. Note that h.Size() must be even (+h % 2 == 0).
  45. inline TString HexDecode(const TStringBuf h) {
  46. return HexDecode(h.data(), h.size());
  47. }