C++ – Bit shifting a character with wrap? C++

bitbit-manipulationbit-shiftc

I have a binary file that will be read in as characters. Each character was bit shifted to the left unknown number of times (assuming with wrap) by someone else. I want to be able to read in each character and then wrap shift to the right (the number of times to shift I guess will have to be figured out manually, because I haven't figured out another way).

So, my current idea is that I read in a character, create a copy with temp and then use XOR:

char letter;    //will hold the read in letter
char temp;      //will hold a copy of the letter
while(file.read(&letter, sizeof(letter)) //letter now holds 00001101
{
    temp = letter;  //temp now holds 00001101
    letter >>= 1;   //shift 1 position to the right, letter now holds 00000110
    temp <<= 7;     //shift to the left by (8-1), which is 7, temp now holds 10000000
    letter ^= temp; //use XOR to get the wrap, letter now holds 10000110
    cout << letter;
}

That makes sense in my exhausted head, but it doesn't work… and I can't figure out why. Size of char is 1 byte, so I figured I only have to mess around with 8 bits.

Any help would be appreciated.

EDIT: Solved. Thanks so much to everyone. Love this community to death, you guys are awesome!

Best Answer

Pay attention to the signess of a char. On many systems it is signed. So your letter >>= 1 is sign filling the shift.

Rotating integers is usually done as follows

letter = ((unsigned char)letter >> 1) | (letter << 7);

As Mark points out in the comments, you can use either OR | or XOR ^.