Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected result in byte representation of a variable

Tags:

c++

c

casting

I scan through the byte representation of an int variable and get somewhat unexpected result.

If I do

int a = 127;
cout << (unsigned int) *((char *)&a);

I get 127 as expected. If I do

int a = 256;
cout << (unsigned int) *((char *)&a + 1);

I get 1 as expected. But if I do

int a = 128;
cout << (unsigned int) *((char *)&a);

I have 4294967168 which is, well… quite fancy.

The question is: is there a way to get 128 when looking at first byte of an int variable which value is 128?

like image 895
Artem Pelenitsyn Avatar asked Nov 07 '12 18:11

Artem Pelenitsyn


1 Answers

For the same reason that (unsigned int)(char)128 is 4294967168: char is signed by default on most commonly used systems. 128 cannot fit in a signed 8-bit quantity, so when you cast it to char, you get -128 (0x80 in hex).

Then, when you cast -128 to an unsigned int, you get 232 - 128, which is 4294967168.

If you want to get +128, then use an unsigned char instead of char.

like image 130
Adam Rosenfield Avatar answered Nov 01 '22 17:11

Adam Rosenfield