You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

92 line
2.0 KiB

  1. #pragma once
  2. #include <iomanip>
  3. #include "hexdump.h"
  4. namespace cppcore
  5. {
  6. /* hexdump */
  7. hexdump::hexdump(
  8. const void * p_data,
  9. size_t p_len,
  10. size_t p_offset,
  11. size_t p_split,
  12. size_t p_newline)
  13. : data (p_data)
  14. , len (p_len)
  15. , offset (p_offset)
  16. , split (p_split)
  17. , newline (p_newline)
  18. { }
  19. void hexdump::print(std::ostream& os) const
  20. {
  21. using namespace ::std;
  22. const uint8_t * p = static_cast<const uint8_t*>(data);
  23. size_t i = 0;
  24. size_t l = 0;
  25. std::string s;
  26. while (i < len)
  27. {
  28. if (i % newline == 0)
  29. {
  30. if (i > 0)
  31. os << endl;
  32. os << hex << setw(8) << setfill('0') << (offset + i);
  33. }
  34. if (l % split == 0)
  35. {
  36. os.put(' ');
  37. s.push_back('|');
  38. }
  39. s.push_back(std::isprint(p[i])
  40. ? static_cast<char>(p[i])
  41. : '.');
  42. os << " " << hex << setw(2) << setfill('0') << static_cast<int>(p[i]);
  43. ++l;
  44. ++i;
  45. if (i % newline == 0)
  46. {
  47. os << " " << s << "|";
  48. s.clear();
  49. l = 0;
  50. }
  51. }
  52. if (l > 0)
  53. {
  54. auto rest = (newline - l);
  55. auto fill = (rest / split);
  56. os << std::string(3 * rest + fill, ' ')
  57. << " " << s << std::string(rest + fill, ' ') << "|";
  58. }
  59. }
  60. }
  61. namespace std
  62. {
  63. /**
  64. * @brief Write the helper class to stream using the << operator.
  65. */
  66. template<typename T_char, typename T_traits>
  67. inline basic_ostream<T_char, T_traits>& operator<< (
  68. basic_ostream<T_char, T_traits>& os,
  69. const cppcore::hexdump& d)
  70. {
  71. d.print(os);
  72. return os;
  73. }
  74. }