Park Chansung
Park Chansung

Reputation: 33

bit masking (char)(0xFFFFFFB8 & 0xFF) doesn't work in c

I am struggling with bit masking or maybe handling bit overflow.

I get data from data stream, and it is stored in char type buffer, and I need to access particular index of the buffer. When I try so, I get unexpected results.

Something like below..

char buffer[BUFFER_SIZE];

/* ...recv from network stream performed... */

printf("buffer[index] = 0x%x\n", buffer[index]); /* => 0xFFFFFFB8 */

char dummyChar = buffer[index] & 0x000000FF;
printf("dummyChar = 0x%x\n", dummyChar); /* => 0xFFFFFFB8 */

The buffer is char type. Why am I getting 32 bits size when I print buffer[index]?

I also masked the buffer[index] with 0x000000FF, but I am still getting 0xFFFFFFB8. Why?

I only want to get 0xB8, can anyone tell me how? I am pretty sure it is 1 byte size..

Upvotes: 3

Views: 1303

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409384

There are two reasons: The first is that when passing an integer type smaller than int it is automatically promoted to int (which possibly sign-extends the value). The second reason is because the printf format "%x" is for printing unsigned int values, not bytes.

For unsigned bytes (unsigned char) you should use the modifier hh as in "%hhx". Then printf will know that the passed value is really a single unsigned byte and not a full unsigned int.

Please see the above linked reference for more details.

Upvotes: 3

2501
2501

Reputation: 25753

The character that you're trying to mask, buffer[index], has a negative value of -72, since the type char is signed on your machine. It's hexadecimal representation is 0xB8.

When the argument buffer[index] is passed to the printf function, integer promotion is performed on it. This means the its type, which is char, is promoted to type int. The representation of -72 in the type int differs from the representation of -72 in type char, on your machine:

In type char, -72 is represented as 0xB8.

In type int, -72 is represented as 0xFFFFFFB8

Performing the and bitwise operation won't change the value:

char dummyChar = buffer[index] & 0x000000FF;

because1: 0xFF & 0xB8 == 0xB8. The character dummyChar will have the same value of -72. Then dummyChar is passed to the printf call and the the same promotion procedure happens as described above.


1 The actual reality is slightly different since integer promotions also happen with bitwise operators, but the outcome is the same. Both types are promoted to int, then the bitwise and is performed and then the result is implicitly converted to char:

0xFFFFFFB8 & 0x000000B8 == 0x000000B8
0x000000B8 == 0xB8

Leaving the value the same as it were before the operation.

Upvotes: 2

Related Questions