Skip to content

Instantly share code, notes, and snippets.

@2bbb
Last active August 29, 2015 14:22
Show Gist options
  • Select an option

  • Save 2bbb/3a3a85b6288cf5d35e3f to your computer and use it in GitHub Desktop.

Select an option

Save 2bbb/3a3a85b6288cf5d35e3f to your computer and use it in GitHub Desktop.
hex_print
#include <cstdio>
#include <cstdint>
template <typename T>
void hex_print(T v) {
switch(sizeof(T)) {
case 1: printf("0x%01X\n", *(reinterpret_cast<uint8_t *>(&v))); break;
case 2: printf("0x%02X\n", *(reinterpret_cast<uint16_t *>(&v))); break;
case 4: printf("0x%04X\n", *(reinterpret_cast<uint32_t *>(&v))); break;
case 8: printf("0x%08llX\n", *(reinterpret_cast<uint64_t *>(&v))); break;
case 16: printf("0x%08llX%08llX\n", *(reinterpret_cast<uint64_t *>(&v) + 1), *(reinterpret_cast<uint64_t *>(&v))); break; // for long double (but this is incorrect...!!)
default: break;
}
}
#include <iostream>
#include "hex_print.h"
using namespace std;
int main(int argc, char *argv[]) {
hex_print('B');
hex_print(4u);
hex_print(9.0f);
hex_print(9.2);
hex_print(9.9l);
hex_print(9.8l);
return EXIT_SUCCESS;
}
@2bbb
Copy link
Author

2bbb commented Jun 18, 2015

omg,

        case 16: printf("0x%08llX%08llX\n", *(reinterpret_cast<uint64_t *>(&v) + 1), *(reinterpret_cast<uint64_t *>(&v))); break;

is wrong...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment