Created
December 2, 2023 02:41
-
-
Save malachib/7817c6d1efe5c182999eed3e0bb57c1c to your computer and use it in GitHub Desktop.
C++ int -> hex
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 <string> | |
// think of 'nibbles' parameter as a kind of hexidecimal version of decimal places | |
std::string int_to_hex(unsigned long value, int nibbles) | |
{ | |
static const char converter[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; | |
// stack allocate C style string, just enough to fit 'nibbles' amount | |
char s[nibbles]; | |
// terminate C-style string | |
s[nibbles] = 0; | |
// move through as many "decimal places" as requested | |
while(nibbles-- > 0) | |
{ | |
// per place, grab the bottom most nibble out of value | |
char c = converter[value & 0xF]; | |
// convert it to a character and store it in C-style string | |
s[nibbles] = c; | |
// bit shift over to grab next nibble | |
value >>= 4; | |
} | |
// convert c style string to c++ style string | |
return { s }; | |
} | |
int main() | |
{ | |
std::cout << "hi2u: " << int_to_hex(10, 4) << std::endl; | |
std::cout << "hi2u: " << int_to_hex(0x1234, 4) << std::endl; | |
std::cout << "hi2u: " << int_to_hex(0x1234, 8) << std::endl; | |
std::cout << "hi2u: " << int_to_hex(0xFF007F, 4) << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment