Advertisement
NickG

to_hex example

Apr 22nd, 2013
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.61 KB | None | 0 0
  1. #include <iomanip>
  2. #include <sstream>
  3. #include <iostream>
  4.  
  5. std::string to_hex(const void *data, const unsigned int size) {
  6.     std::stringstream stream;
  7.     stream << std::uppercase << std::hex;
  8.     const unsigned char *bytes = static_cast<const unsigned char *>(data);
  9.     for (unsigned int i = 0; i<size; ++i) {
  10.         stream << std::setfill('0') << std::setw(2) << static_cast<const int>(bytes[i]) << " ";
  11.     }
  12.     return stream.str().substr(0, stream.str().size()-1);
  13. }
  14.  
  15. int main() {
  16.     int myint = 20;
  17.     std::string myhexstring = to_hex(&myint, sizeof(myint));
  18.     std::cout << myhexstring << std::endl;
  19. }
  20.  
  21. //Output
  22. //14 00 00 00
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement