glavmonter

hexdump

Jul 23rd, 2020
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.99 KB | None | 0 0
  1. #ifndef TESTJSON_HEXDUMP_HPP
  2. #define TESTJSON_HEXDUMP_HPP
  3.  
  4. #include <ostream>
  5. #include <string>
  6.  
  7. namespace neolib
  8. {
  9.     template<class Elem, class Traits>
  10.     inline void hex_dump(const void* aData, std::size_t aLength, std::basic_ostream<Elem, Traits>& aStream, std::size_t offset = 0, std::size_t aWidth = 16)
  11.     {
  12.         const char* const start = static_cast<const char*>(aData);
  13.         const char* const end = start + aLength;
  14.         const char* line = start;
  15.         while (line != end)
  16.         {
  17.             aStream.width(4);
  18.             aStream.fill('0');
  19.             aStream << std::hex << (line - start) + offset << ": ";
  20.             std::size_t lineLength = std::min(aWidth, static_cast<std::size_t>(end - line));
  21.             for (std::size_t pass = 1; pass <= 2; ++pass)
  22.             {
  23.                 for (const char* next = line; next != end && next != line + aWidth; ++next)
  24.                 {
  25.                     char ch = *next;
  26.                     switch(pass)
  27.                     {
  28.                         case 2:
  29.                             aStream << (ch < 32 ? '.' : ch);
  30.                             break;
  31.  
  32.                         case 1:
  33.                             if (next != line)
  34.                                 aStream << " ";
  35.  
  36.                             if (next - line == 8) {
  37.                                 aStream << " ";
  38.                             }
  39.  
  40.                             aStream.width(2);
  41.                             aStream.fill('0');
  42.                             aStream << std::hex << std::uppercase << static_cast<int>(static_cast<unsigned char>(ch));
  43.                             break;
  44.                     }
  45.                 }
  46.                 if (pass == 1 && lineLength != aWidth)
  47.                     aStream << std::string((aWidth - lineLength)*3 + 1, ' ');
  48.                 aStream << "   ";
  49.             }
  50.             aStream << std::endl;
  51.             line = line + lineLength;
  52.         }
  53.     }
  54. }
  55.  
  56. #endif //TESTJSON_HEXDUMP_HPP
Add Comment
Please, Sign In to add comment