I am writing a program that needs to take an array of size n and convert that into it’s hex value as follows:
int a[] = { 0, 1, 1, 0 };
I would like to take each value of the array to represent it as binary and convert it to a hex value. In this case:
0x6000000000000000; // 0110...0
it also has to be packed to the right with 0’s to be 64 bits (i am on a 64 bit machine).
Or i could also take the array elements, convert to decimal and convert to hexadecimal it that’s easier… What you be the best way of doing this in C++?
(this is not homework)
The following assumes that your
a[]will only ever use 0 and 1 to represent bits. You’ll also need to specify the array length,sizeof(a)/sizeof(int)can be used in this case, but not for heap allocated arrays. Also,resultwill need to be a 64bit integer type.If you want to see what it looks like in hex, you can use
(s)printf( "%I64x", result )