hexdump.c 2.1 KB

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