fork(3) download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <sstream>
  4. #include <climits>
  5. #include <cstdint>
  6. #include <type_traits>
  7.  
  8. namespace hex_out_helper {
  9. constexpr int HEX_DIGIT_BITS = 4; // One hex digit = 4 bits.
  10. constexpr int HEX_BASE_CHARS = 2; // For the "0x".
  11.  
  12. template<typename T> struct CharCheck {
  13. using type = T;
  14. };
  15.  
  16. template<> struct CharCheck<signed char> {
  17. using type = char;
  18. };
  19.  
  20. template<> struct CharCheck<unsigned char> {
  21. using type = char;
  22. };
  23.  
  24. template<typename T> using CharChecker = typename CharCheck<T>::type;
  25. } // namespace hex_out_helper
  26.  
  27.  
  28. template<typename T> std::string hex_out_s(T val) {
  29. using namespace hex_out_helper;
  30.  
  31. std::stringstream sformatter;
  32. sformatter << std::hex
  33. << std::internal
  34. << std::showbase
  35. << std::setfill('0')
  36. << std::setw((sizeof(T) * CHAR_BIT / HEX_DIGIT_BITS) + HEX_BASE_CHARS)
  37. << (std::is_same<CharChecker<T>, char>{} ? static_cast<int>(val) : val);
  38. return sformatter.str();
  39. }
  40.  
  41. int main() {
  42. uint32_t hexU32 = 0x0f;
  43. int hexI = 0x3c;
  44. unsigned short hexUS = 0x12;
  45. char hexC = 0xf;
  46. unsigned char hexUC = 0xa;
  47. signed char hexSC = 0x3;
  48.  
  49. std::cout << "uint32_t: " << hex_out_s(hexU32) << std::endl;
  50. std::cout << "int: " << hex_out_s(hexI) << std::endl;
  51. std::cout << "unsigned short: " << hex_out_s(hexUS) << std::endl;
  52. std::cout << "char: " << hex_out_s(hexC) << std::endl;
  53. std::cout << "unsigned char: " << hex_out_s(hexUC) << std::endl;
  54. std::cout << "signed char: " << hex_out_s(hexSC) << std::endl;
  55. std::cout << "Decimal rvalues, too: " << hex_out_s(29) << std::endl;
  56. std::cout << "And a long long: " << hex_out_s(LLONG_MAX) << std::endl;
  57. }
Success #stdin #stdout 0s 3424KB
stdin
Standard input is empty
stdout
uint32_t: 0x0000000f
int: 0x0000003c
unsigned short: 0x0012
char: 0x0f
unsigned char: 0x0a
signed char: 0x03
Decimal rvalues, too: 0x0000001d
And a long long: 0x7fffffffffffffff