Advertisement
pneave

Print unsigned char as string of hex numbers.

Feb 8th, 2018
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. //-----------------------------------------------------------------------------
  2. //
  3. // %%HeaderFileHeader%%
  4. //
  5. //-----------------------------------------------------------------------------
  6. #pragma once
  7. //-----------------------------------------------------------------------------
  8. #include <iomanip>
  9. #include <iterator>
  10. #include <vector>
  11. //-----------------------------------------------------------------------------
  12.  
  13. //
  14. // Display unsigned char as string of hex numbers.
  15. // Usage:
  16. //       std::cout << hex(16);
  17. //       std::cout << hex(0x10);
  18. //       std::cout << hex({42, 43, 44});
  19. //
  20.  
  21.  
  22. struct HexCharStruct
  23. {
  24.    unsigned char c;
  25.    HexCharStruct(unsigned char _c) : c(_c) { }
  26. };
  27.  
  28. inline std::ostream& operator<<(std::ostream& o, const HexCharStruct& _hs)
  29. {
  30.    return (o << "0x" << std::setfill ('0') << std::setw(2) << std::hex << (int)_hs.c);
  31. }
  32.  
  33. inline std::ostream& operator<<(std::ostream& o, const std::vector<HexCharStruct> _vhs)
  34. {
  35.    for (auto&& hs : _vhs) {
  36.       o << hs;
  37.       if (&hs != &_vhs.back()) o << " ";
  38.    }
  39.    return o;
  40. }
  41.  
  42. inline HexCharStruct hex(unsigned char _c)
  43. {
  44.    return HexCharStruct(_c);
  45. }
  46.  
  47. inline std::vector<HexCharStruct> hex(const std::vector<unsigned char> _vc)
  48. {
  49.    std::vector<HexCharStruct> vec;
  50.    for (auto c : _vc) {
  51.       vec.push_back(c);
  52.    }
  53.    return vec;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement