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
@jedahan
oh... sorry, i find your comment now...
1.0 is typed double on every C/C++/Obj-C enviroment.
and, definition of double is 64bit in IEEE 754. therefore, convert to uint64_t.
if we wanna use float definitely, we have to add suffix f.
then, always it is typed float and convert to uint32_t.
so, i like adding suffix f when writing oF codes. because oF use float basically.
(but, most people does not seem to mind... 😿 )
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
So the default for an unspecified floating point number (92) is uint64_t / native word size? And if you specify
fis always uint32_t? Interesting that specifyingfwill actually reduce accuracy (at least on 64-bit systems).Such a great exploration. I will continue writing about it when I get back from Kansai :)