hexdump.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* SPDX-License-Identifier: GPL-2.0+ */
  2. /*
  3. * Copyright (C) 2018 Synopsys, Inc. All rights reserved.
  4. *
  5. */
  6. #ifndef HEXDUMP_H
  7. #define HEXDUMP_H
  8. #include <linux/ctype.h>
  9. #include <linux/types.h>
  10. enum {
  11. DUMP_PREFIX_NONE,
  12. DUMP_PREFIX_ADDRESS,
  13. DUMP_PREFIX_OFFSET
  14. };
  15. extern const char hex_asc[];
  16. #define hex_asc_lo(x) hex_asc[((x) & 0x0f)]
  17. #define hex_asc_hi(x) hex_asc[((x) & 0xf0) >> 4]
  18. static inline char *hex_byte_pack(char *buf, u8 byte)
  19. {
  20. *buf++ = hex_asc_hi(byte);
  21. *buf++ = hex_asc_lo(byte);
  22. return buf;
  23. }
  24. /**
  25. * hex_to_bin - convert a hex digit to its real value
  26. * @ch: ascii character represents hex digit
  27. *
  28. * hex_to_bin() converts one hex digit to its actual value or -1 in case of bad
  29. * input.
  30. */
  31. static inline int hex_to_bin(char ch)
  32. {
  33. if ((ch >= '0') && (ch <= '9'))
  34. return ch - '0';
  35. ch = tolower(ch);
  36. if ((ch >= 'a') && (ch <= 'f'))
  37. return ch - 'a' + 10;
  38. return -1;
  39. }
  40. /**
  41. * hex2bin - convert an ascii hexadecimal string to its binary representation
  42. * @dst: binary result
  43. * @src: ascii hexadecimal string
  44. * @count: result length
  45. *
  46. * Return 0 on success, -1 in case of bad input.
  47. */
  48. static inline int hex2bin(u8 *dst, const char *src, size_t count)
  49. {
  50. while (count--) {
  51. int hi = hex_to_bin(*src++);
  52. int lo = hex_to_bin(*src++);
  53. if ((hi < 0) || (lo < 0))
  54. return -1;
  55. *dst++ = (hi << 4) | lo;
  56. }
  57. return 0;
  58. }
  59. /**
  60. * bin2hex - convert binary data to an ascii hexadecimal string
  61. * @dst: ascii hexadecimal result
  62. * @src: binary data
  63. * @count: binary data length
  64. */
  65. static inline char *bin2hex(char *dst, const void *src, size_t count)
  66. {
  67. const unsigned char *_src = src;
  68. while (count--)
  69. dst = hex_byte_pack(dst, *_src++);
  70. return dst;
  71. }
  72. int hex_dump_to_buffer(const void *buf, size_t len, int rowsize, int groupsize,
  73. char *linebuf, size_t linebuflen, bool ascii);
  74. void print_hex_dump(const char *prefix_str, int prefix_type, int rowsize,
  75. int groupsize, const void *buf, size_t len, bool ascii);
  76. void print_hex_dump_bytes(const char *prefix_str, int prefix_type,
  77. const void *buf, size_t len);
  78. #endif /* HEXDUMP_H */