Park Chansung Park Chansung - 1 year ago 88
C Question

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

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
type. Why am I getting 32 bits size when I print buffer[index]?

I also masked the
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..

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download