hexdump.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. #include "logging.h"
  22. #define hex_print(p) applog(LOG_DEBUG, "%s", p)
  23. static char nibble[] = {
  24. '0', '1', '2', '3', '4', '5', '6', '7',
  25. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  26. #define BYTES_PER_LINE 0x10
  27. void hexdump(const void *vp, unsigned int len)
  28. {
  29. const unsigned char *p = vp;
  30. unsigned int i, addr;
  31. unsigned int wordlen = sizeof(void*);
  32. unsigned char v, line[BYTES_PER_LINE * 5];
  33. for (addr = 0; addr < len; addr += BYTES_PER_LINE) {
  34. /* clear line */
  35. for (i = 0; i < sizeof(line); i++) {
  36. if (i == wordlen * 2 + 52 ||
  37. i == wordlen * 2 + 69) {
  38. line[i] = '|';
  39. continue;
  40. }
  41. if (i == wordlen * 2 + 70) {
  42. line[i] = '\0';
  43. continue;
  44. }
  45. line[i] = ' ';
  46. }
  47. /* print address */
  48. for (i = 0; i < wordlen * 2; i++) {
  49. v = addr >> ((wordlen * 2 - i - 1) * 4);
  50. line[i] = nibble[v & 0xf];
  51. }
  52. /* dump content */
  53. for (i = 0; i < BYTES_PER_LINE; i++) {
  54. int pos = (wordlen * 2) + 3 + (i / 8);
  55. if (addr + i >= len)
  56. break;
  57. v = p[addr + i];
  58. line[pos + (i * 3) + 0] = nibble[v >> 4];
  59. line[pos + (i * 3) + 1] = nibble[v & 0xf];
  60. /* character printable? */
  61. line[(wordlen * 2) + 53 + i] =
  62. (v >= ' ' && v <= '~') ? v : '.';
  63. }
  64. hex_print(line);
  65. }
  66. }