简体   繁体   English

具有无符号字符的位运算符

[英]bit operators with unsigned characters

unsigned char 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. 我确实理解位运算符是如何工作的,但我不理解x的二进制表示。

How is a = 208? a = 208怎么样?

93 = 01011101

向左移动4位并保留以下内容(结果中只有8位):

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

1101 0000 in decimal is 208. 十进制的1101 0000是208。

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

ie 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 x << 4是x * 16,因此x * 16 = 93 * 16 = 1488

but a is an unsigned char (ie 0<=a<256), so a = 1488 modulo 256 = 208 但是a是无符号字符(即0 <= a <256),因此a = 1488模256 = 208

That's because an unsigned char can only be as big as 255(1111 1111 in binary). 那是因为unsigned char只能大到255(二进制1111 1111)。 If a number is left-shifted, all bits that go out of its bounds are lost. 如果一个数字被左移,那么超出其边界的所有位都将丢失。 0b11111111 << 1 = 0b11111110 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. 所以,如果你得到93的二进制(0101 1101)并且左移4次你会得到1101 0000-最左边的4位永远丢失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM