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?
For the same reason that
(unsigned int)(char)128is 4294967168:charis signed by default on most commonly used systems. 128 cannot fit in a signed 8-bit quantity, so when you cast it tochar, 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 charinstead ofchar.