fork download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <vector>
  4. #include <string>
  5. #include <iomanip>
  6.  
  7. // generic iterator range
  8. template<typename Iter>
  9. std::string hex_str(Iter beg, Iter end)
  10. {
  11. std::stringstream ss;
  12. ss << "[ " << std::hex << std::setfill('0');
  13. while (beg != end)
  14. ss << std::setw(2) << (static_cast<unsigned short>(*beg++) & 0xFF) << " ";
  15. ss << "]" << std::dec;
  16. return ss.str();
  17. }
  18.  
  19. // fixed array
  20. template<typename T, size_t N>
  21. std::string hex_str(const T(&ar)[N])
  22. {
  23. return hex_str(std::begin(ar), std::end(ar));
  24. }
  25.  
  26. // sequence container
  27. template<template<class,class...> class S, class T, class... Args>
  28. std::string hex_str(const S<T,Args...>& s)
  29. {
  30. return hex_str(s.begin(), s.end());
  31. }
  32.  
  33. int main()
  34. {
  35. unsigned char ptr[] = {0xff, 0x00, 0x4d, 0xff, 0xdd};// <--see here, 0x00 is the issue.
  36. std::cout << hex_str(ptr) << std::endl;
  37.  
  38. std::vector<unsigned char> vec{ 0x01, 0x02, 0x03, 0x04, 0x05 };
  39. std::cout << hex_str(vec) << std::endl;
  40.  
  41. std::string str{ 0x10, 0x20, 0x30, 0x40, 0x50, 0x00 };
  42. std::cout << hex_str(str) << std::endl;
  43.  
  44. return 0;
  45. }
  46.  
Success #stdin #stdout 0s 3436KB
stdin
Standard input is empty
stdout
[ ff 00 4d ff dd ]
[ 01 02 03 04 05 ]
[ 10 20 30 40 50 00 ]