By using filestreaming in c++, I have read a string in the binary file into a buffer (4 bytes). I know that the buffer contains “89abcdef“. The buffer is such that:
buffer[0] = 89
buffer[1] = ab
buffer[2] = cd
buffer[3] = ef
Now, I want to recover these numbers into one single hex number 0x89abcdef. However, this is not as simple as I thought. I tried the following code:
int num = 0;
num |= buffer[0];
num <<= 24;
cout << num << endl;
at this point, num is displayed to be
ea000000
When I tried the same algorithm for the second element of the buffer:
num = 0;
num |= buffer[1];
num <<= 16;
cout << num << endl;
output:
ffcd0000
The ff in front of the cd is highly inconvenient for me to add them all together (I was planning to make it something looks like 00cd0000, and add it to the first num).
Could anyone help me to recover the hex number 0x89abcdef? Thanks.
Don’t modify the actual number until the end:
buffer [0] << 24gives you your first result, which is combined with the second result independent of the first, and so on.Also, as pointed out, operations like this should be done on unsigned numbers, so that the signing doesn’t interfere with the result.