猿问

Golang 中的移位指令

go规范说:


<<    left shift             integer << unsigned integer

如果左侧的类型为 uint8:


var x uint8 = 128

fmt.Println(x << 8)      // it got 0, why ?

fmt.Println(int(x)<<8)   // it got 32768, sure

问题:


当 x 是 uint8 类型时,为什么没有编译错误?

为什么x << 8得到结果0

对于 C/C++,


unsigned int a = 128;

printf("%d",a << 8); // result is 32768.

谁能解释一下?谢谢你。


largeQ
浏览 288回答 2
2回答

慕斯王

左移运算符会将数字中的二进制数字向左移动 X 位。这具有将 X 个0's添加到右侧的效果,数字 Aunit8仅包含8位,因此当您拥有128变量时x =&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 1000 0000 == 128x << 8x=&nbsp; &nbsp;1000 0000 0000 0000 == 32768由于uint8只保存 8 位,我们取最右边的 8 位,即x =&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 0000 0000 == 0使用 an 获得正确数字的原因int是 anint至少有 16 位的存储空间,并且很可能在您的系统上有 32 位。这足以存储整个结果。
随时随地看视频慕课网APP

相关分类

Go
我要回答