I’m attempting to implement circular bit-shifting in C++. It kind of works, except after a certain point I get a bunch of zeroes.
for (int n=0;n<12;n++) {
unsigned char x=0x0f;
x=((x<<n)|(x>>(8-n))); //chars are 8 bits
cout<<hex<<"0x"<<(int)x<<endl;
}
My output is:
0xf
0x1e
0x3c
0x78
0xf0
0xe1
0xc3
0x87
0xf
0x0
0x0
0x0
As you can see, I start getting 0x0’s instead of the expected 0x1e, 0x3c, etc.
If I expand the for loop to iterate 60 times or so, the numbers come back correctly (after a bunch of zeroes.)
I’m assuming that a char houses a big space, and the “gaps” of unused data are zeroes. My understanding is a bit limited, so any suggestions would be appreciated. Is there a way to toss out those zeroes?
Shifting by a negative amount is undefined behavior.
You loop from
0to12, but you have an8 - nin your shifts. So that will go negative.If you want to handle
n > 8, you’ll need to take a modulus by 8. (assuming you want 8-bit circular shift.)