Last active
August 29, 2015 14:22
-
-
Save 2bbb/3a3a85b6288cf5d35e3f to your computer and use it in GitHub Desktop.
hex_print
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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; | |
| } |
Author
Author
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
@jedahan
oh... sorry, i find your comment now...
1.0is typeddoubleon every C/C++/Obj-C enviroment.and, definition of
doubleis 64bit in IEEE 754. therefore, convert to uint64_t.if we wanna use
floatdefinitely, we have to add suffixf.then, always it is typed
floatand convert touint32_t.so, i like adding suffix
fwhen writing oF codes. because oF use float basically.(but, most people does not seem to mind... 😿 )