hexdump.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * hexdump implementation without depenecies to *printf()
  3. * output is equal to 'hexdump -C'
  4. * should be compatible to 64bit architectures
  5. *
  6. * Copyright (c) 2009 Daniel Mack <daniel@caiaq.de>
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. #define hex_print(p) applog(LOG_DEBUG, "%s", p)
  22. static char nibble[] = {
  23. '0', '1', '2', '3', '4', '5', '6', '7',
  24. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  25. #define BYTES_PER_LINE 0x10
  26. static void hexdump(const uint8_t *p, unsigned int len)
  27. {
  28. unsigned int i, addr;
  29. unsigned int wordlen = sizeof(void*);
  30. unsigned char v, line[BYTES_PER_LINE * 5];
  31. for (addr = 0; addr < len; addr += BYTES_PER_LINE) {
  32. /* clear line */
  33. for (i = 0; i < sizeof(line); i++) {
  34. if (i == wordlen * 2 + 52 ||
  35. i == wordlen * 2 + 69) {
  36. line[i] = '|';
  37. continue;
  38. }
  39. if (i == wordlen * 2 + 70) {
  40. line[i] = '\0';
  41. continue;
  42. }
  43. line[i] = ' ';
  44. }
  45. /* print address */
  46. for (i = 0; i < wordlen * 2; i++) {
  47. v = addr >> ((wordlen * 2 - i - 1) * 4);
  48. line[i] = nibble[v & 0xf];
  49. }
  50. /* dump content */
  51. for (i = 0; i < BYTES_PER_LINE; i++) {
  52. int pos = (wordlen * 2) + 3 + (i / 8);
  53. if (addr + i >= len)
  54. break;
  55. v = p[addr + i];
  56. line[pos + (i * 3) + 0] = nibble[v >> 4];
  57. line[pos + (i * 3) + 1] = nibble[v & 0xf];
  58. /* character printable? */
  59. line[(wordlen * 2) + 53 + i] =
  60. (v >= ' ' && v <= '~') ? v : '.';
  61. }
  62. hex_print(line);
  63. }
  64. }