return 0
return 0

Reputation: 4366

Hex bitwise operation in c++

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.

Upvotes: 0

Views: 2917

Answers (2)

jwismar
jwismar

Reputation: 12258

For all of your bitwise operations, you're going to want to use unsigned int instead of int. This way you can avoid the kinds of sign-extension problems you're seeing.

Upvotes: 2

Qaz
Qaz

Reputation: 61900

Don't modify the actual number until the end:

num = buffer [0] << 24 | buffer [1] << 16 | buffer [2] << 8 | buffer [3];

buffer [0] << 24 gives 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.

Upvotes: 4

Related Questions