hexdump.c 2.0 KB

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