pneave icon

Print unsigned char as string of hex numbers.

pneave | PRO | 02/08/18 02:17:42 PM UTC | 0 ⭐ | 295 👁️ | Never ⏰ | []
C++ |

1.33 KB

|

None

|

0 👍

/

0 👎

//-----------------------------------------------------------------------------
//
// %%HeaderFileHeader%%
//
//-----------------------------------------------------------------------------
#pragma once
//-----------------------------------------------------------------------------
#include <iomanip>
#include <iterator>
#include <vector>
//-----------------------------------------------------------------------------
 
//
// Display unsigned char as string of hex numbers.
// Usage:
//       std::cout << hex(16);
//       std::cout << hex(0x10);
//       std::cout << hex({42, 43, 44});
//
 
 
struct HexCharStruct
{
   unsigned char c;
   HexCharStruct(unsigned char _c) : c(_c) { }
};
 
inline std::ostream& operator<<(std::ostream& o, const HexCharStruct& _hs)
{
   return (o << "0x" << std::setfill ('0') << std::setw(2) << std::hex << (int)_hs.c);
}
 
inline std::ostream& operator<<(std::ostream& o, const std::vector<HexCharStruct> _vhs)
{
   for (auto&& hs : _vhs) {
      o << hs;
      if (&hs != &_vhs.back()) o << " ";
   }
   return o;
}
 
inline HexCharStruct hex(unsigned char _c)
{
   return HexCharStruct(_c);
}
 
inline std::vector<HexCharStruct> hex(const std::vector<unsigned char> _vc)
{
   std::vector<HexCharStruct> vec;
   for (auto c : _vc) {
      vec.push_back(c);
   }
   return vec;
}

Comments