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!
<< 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.