4

I know this is a common problem, and I cannot figure out why I am having so much trouble. I am trying to convert a line from an IDL code to c++

IDL:

for i = 0,7 do begin

    b = ishfy(b,1)
    print,b

endfor

My C++ code:

    for(int i = 0; i < 7; i++)
    {
        b = b << 1;
        cout << b;
    }

My initial b is 255, and I expect to receive 254, 252, ect. Instead my first bit shift returns 510. I assume my problem is not converting b to a binary form before shifting. Is this correct? And if so how do I fix it?

Thanks in advance!

4

2 回答 2

5

<< 向左移动。如果 B 最初是 255(二进制 11111111),然后将其向左移动一位,您将得到 111111110(在大多数机器上,int 是 32 位宽,因此有 0 的空间),即十进制的 510。

因此,该程序 100% 正常运行。

如果您希望它“砍掉”高位,则将 b 设为 8 位宽的类型,例如 char,或者将其与 0xFF 相加。

于 2013-10-08T20:23:00.880 回答
1

您似乎想清除最低有效位。左移运算符<<不这样做。

在这种情况下,您可以执行以下操作:

for(int i = 0; i < 7; i++)
{
    b &= (b - 1);
    cout << b;
}

所以你有了:

1st it: 11111111 & 11111110 = 11111110 = 254
2nd it: 11111110 & 11111101 = 11111100 = 252
3rd it: 11111100 & 11111011 = 11111000 = 248
4th it: 11111000 & 11110111 = 11110000 = 240

……

于 2013-10-08T20:28:29.037 回答