开发者

bit operators with unsigned characters

开发者 https://www.devze.com 2023-02-12 09:54 出处:网络
unsigned ch开发者_如何学运维ar x = 93; unsigned char a = x << 4; printf(\"a = %d\\n\", a);
unsigned ch开发者_如何学运维ar x = 93;
unsigned char a = x << 4;
printf("a = %d\n", a);

I do understand how bit operators work but I don't understand the binary representation of x.

How is a = 208?


93 = 01011101

Shift that left 4 bits and it leaves the following (only 8 bits in your result):

11010000 = 208


x = 93 = 0x5D = 0101 1101
         << 4 = 1101 0000

1101 0000 in decimal is 208.


93 = 0x5d
0x5d << 4 = 0x5d0
0x5d0 & 0xff = 0xd0
0xd0 = 208

i.e. what has happened here is that the top bits have been cut off.


Mathematically it corresponds to the following:

x<<4 is x*16, so x*16 = 93*16 = 1488

but a is an unsigned char (ie 0<=a<256), so a = 1488 modulo 256 = 208


That's because an unsigned char can only be as big as 255(1111 1111 in binary). If a number is left-shifted, all bits that go out of its bounds are lost. 0b11111111 << 1 = 0b11111110

So, if you get 93 in binary(0101 1101) and left shift it 4 times you'll get 1101 0000 -the 4 leftmost bits are forever lost.

0

精彩评论

暂无评论...
验证码 换一张
取 消