Skip to content

Instantly share code, notes, and snippets.

@malachib
Created December 2, 2023 02:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malachib/7817c6d1efe5c182999eed3e0bb57c1c to your computer and use it in GitHub Desktop.
Save malachib/7817c6d1efe5c182999eed3e0bb57c1c to your computer and use it in GitHub Desktop.
C++ int -> hex
#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