Question

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!

Was it helpful?

Solution

<< shifts to the left. If B is initially 255 (binary 11111111) and you shift it one to the left you get 111111110 (on most machines, an int is 32 bits wide so there is room for that 0), which is 510 in decimal.

So, this program is working 100% properly.

If you want it to "chop off" the higher bits make b an 8-bit wide type, such as a char, or AND it with 0xFF.

OTHER TIPS

It seems like you want to clear the lowest significant bit. The left shift operator << does not do that.

In this case you can do the following:

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

So you have:

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

....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top