Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bruceoutdoors
Created May 18, 2017 13:52
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 bruceoutdoors/88755edf8b4bdefd0021e7c7c01cdb44 to your computer and use it in GitHub Desktop.
Save bruceoutdoors/88755edf8b4bdefd0021e7c7c01cdb44 to your computer and use it in GitHub Desktop.
from int cast to byte, from byte extract hex values.
#include <iostream>
using namespace std;
struct Byte {
void to4Bits(char c)
{
lo = c >> 4;
hi = c & 0x0F;
}
unsigned int lo : 4, hi : 4;
} Byte;
void byteTohex(char c, char hex[2])
{
static const char hexTable[] = {
'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'A', 'B',
'C', 'D', 'E', 'F'
};
Byte.to4Bits(c);
hex[0] = hexTable[Byte.lo];
hex[1] = hexTable[Byte.hi];
}
int main()
{
char c[2];
unsigned int h = 0xDEADBEEF;
char *karr = (char *)&h;
for (int i = 3; i >= 0; --i) {
byteTohex(karr[i] , c);
cout << c;
}
cout << endl;
uint64_t w = 0xFADEBED012345678;
char *warr = (char *)&w;
for (int i = 7; i >= 0; --i) {
byteTohex(warr[i] , c);
cout << c;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment