fork download
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. std::string integer_to_hex(const int input)
  6. {
  7. static const char* const lut = "0123456789ABCDEF";
  8.  
  9. const size_t len = sizeof(int);
  10.  
  11. // Convert integer into bytes
  12. unsigned char byte_array[len];
  13. byte_array[0] = (input & 255);
  14. byte_array[1] = ((input >> 8) & 255);
  15. byte_array[2] = ((input >> 16) & 255);
  16. byte_array[3] = ((input >> 24) & 255);
  17.  
  18. std::string output;
  19.  
  20. // Each character in hex takes 2 bytes therefore, double space.
  21. output.reserve(2 * len);
  22.  
  23. for (size_t i = 0; i < sizeof(int); ++i)
  24. {
  25. // Shift four places to right and get the first hex byte
  26. output.push_back(lut[byte_array[i] >> 4]);
  27.  
  28. // Get the first four bites and use it to get hex index
  29. output.push_back(lut[byte_array[i] & 15]);
  30.  
  31. // insert a space character to separate hex characters
  32. output.push_back(32);
  33. }
  34. return output;
  35. }
  36.  
  37. int main() {
  38. cout << integer_to_hex(1000) << endl;
  39. return 0;
  40. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
E8 03 00 00