DDS_Octet位移问题:在C ++中,向右移位加1而不是0

时间:2020-08-02 22:28:35

标签: c++ bit-shift bitset data-distribution-service

我在移位时遇到问题,我似乎无法理解发生了什么。我可以很好地将位向左移,但是我无法将位向右移。看一下发生了什么:

向右移动(按预期工作):

// bits is a char that = 00011000

// Shift the bits to the left
bits = bits << 3;

// Print the bits
std::bitset<8> x(bits);
std::cout << "Shifted Bits: " << x << std::endl;

由于'00011000'已向左移3位,因此产生的预期输出为 11000000

当我尝试向右移动时,看起来好像添加了1而不是0,但是:

// bits = 11000000 from the previous operation

// Shift the bits to the right
bits = bits >> 5;

// Print the bits
std::bitset<8> y(bits);
std::cout << "Shifted (right) bits: " << y << std::endl;

当我试图将'11000000'右移5位时,当预期输出为'00000110'时,这会产生意外的输出 11111110

是否有解释/原因说明为什么移位运算符在我向左移动时会在新的空格上加0,而在我向右移动时又在新的空格上加1?

谢谢!

编辑:

我知道发生了什么事。我正在从DDS_Octets数组中提取位,但是我使用了char作为bits变量。看起来像这样:

DDS_Octet* buffer_ = new DDS_Octet(BUFFSIZE); 
fill_buffer(buffer_);

// Here is where the issue is
// I am implicitly casting a DDS_Octet to a char which is a no-no
char bits = buffer_[0];

// The code above now happens here

当我将“ bits”设置为与缓冲区相同的类型时,不再需要添加1而不是0的问题。

如果有人遇到与我相同的问题并偶然发现,我会把它留在这里。

1 个答案:

答案 0 :(得分:1)

您将char用作位。 char是签名的还是未签名的,取决于平台。您应该使用unsigned char获得更期望的行为。