Download | Plain Text | No Line Numbers


  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <ctype.h>
  4.  
  5. void hex_dump(void *data, int size)
  6. {
  7. /* dumps size bytes of *data to stdout. Looks like:
  8.   * [0000] 75 6E 6B 6E 6F 77 6E 20
  9.   * 30 FF 00 00 00 00 39 00 unknown 0.....9.
  10.   * (in a single line of course)
  11.   */
  12.  
  13. unsigned char *p = data;
  14. unsigned char c;
  15. int n;
  16. char bytestr[20] = {0};
  17. char addrstr[10] = {0};
  18. char hexstr[ 16*3 + 5 + 20] = {0};
  19. char charstr[16*1 + 5] = {0};
  20. for (n=1;n<=size;n++)
  21. {
  22. if (n%8 == 1)
  23. {
  24. /* store address for this line */
  25. snprintf(addrstr, sizeof(addrstr), "%.4x",
  26. ((unsigned int)p-(unsigned int)data) );
  27. }
  28.  
  29. c = *p;
  30. if (isalnum(c) == 0)
  31. c = '.';
  32.  
  33. /* store hex str (for left side) */
  34. snprintf(bytestr, sizeof(bytestr), "0x%02x ", *p);
  35. strncat(hexstr, bytestr, sizeof(hexstr)-strlen(hexstr)-1);
  36.  
  37. /* store char str (for right side) */
  38. snprintf(bytestr, sizeof(bytestr), "%c", c);
  39. strncat(charstr, bytestr, sizeof(charstr)-strlen(charstr)-1);
  40.  
  41. if (n%8 == 0)
  42. {
  43. /* line completed */
  44. fprintf(stderr, "[%4.4s] %-65.65s %s\n", addrstr, hexstr, charstr);
  45. hexstr[0] = 0;
  46. charstr[0] = 0;
  47. }
  48. else if (n%8 == 0)
  49. {
  50. /* half line: add whitespaces */
  51. strncat(hexstr, " ", sizeof(hexstr)-strlen(hexstr)-1);
  52. strncat(charstr, " ", sizeof(charstr)-strlen(charstr)-1);
  53. }
  54. p++; /* next byte */
  55. }
  56.  
  57. if (strlen(hexstr) > 0)
  58. {
  59. /* print rest of buffer if not empty */
  60. fprintf(stderr, "[%4.4s] %-65.65s %s\n", addrstr, hexstr, charstr);
  61. }
  62. }
  63.  
  64.