简体   繁体   English

右移位的奇怪行为

[英]Strange behaviour with right bit shift

Could someone explain me why the following code: 有人可以解释我为什么以下代码:

#include <iostream>
#include <bitset>

int main()
{
    unsigned char i = 2;
    std::cout<<std::bitset<8>((~static_cast<unsigned char>(0)) << i)<<std::endl;
    std::cout<<std::bitset<8>((~static_cast<unsigned char>(0)) >> i)<<std::endl;
    return 0;
}

Produces: 生产:

11111100
11111111

and not: 并不是:

11111100
00111111

Before ~ is done static_cast<unsigned char>(0) is converted to int (integer promotion happens), so after ~ it becomes all-one bits int . ~完成之前, static_cast<unsigned char>(0)被转换为int (整数提升发生),所以在~之后它变为全一位int This then is shifted and truncated to 8 bits in bitset. 然后将其移位并截断为bitset中的8位。

On right-shifts, signed values are zero-filled on if the most significant bit is 0, and one-filled if the most significant bit is 1. 在右移时,如果最高有效位为0,则有符号值为零,如果最高有效位为1,则有符号值为零。

Using unsigned values forces zero-filling on right shifts. 使用无符号值会强制右移零填充。

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

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