Bit shifting a character with wrap? C++

倖福魔咒の 提交于 2019-12-23 09:12:59

问题


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!


回答1:


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




回答2:


The statement temp <<= 7 is losing the bits that you want to wrap. You will need to loop shifting left one bit at a time. First checking the most significant char bit and if set moving it to the right most bit before doing the shift.




回答3:


I'd be inclined to use a larger integral type:

unsigned val = (unsigned)letter & 0xFF;
val |= val << 8;

Now you just have to shift values in val, without any additional code to wrap the high bits back in.



来源:https://stackoverflow.com/questions/15648116/bit-shifting-a-character-with-wrap-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!