我有一个二进制文件,将作为字符读入。每个字符都被其他人向左移动了未知次数(假设换行)。我希望能够读入每个字符,然后将 shift 换行到右边(我想换行的次数必须手动计算,因为我还没有想出另一种方法)。
所以,我目前的想法是读入一个字符,用 temp 创建一个拷贝,然后使用 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;
}
这在我疲惫的头脑中是有道理的,但它不起作用……而且我不明白为什么。 char 的大小是 1 个字节,所以我想我只需要弄乱 8 位。
最佳答案
注意字符的符号。在许多系统上它被签名。所以你的 letter >>= 1
是填充符号。
旋转整数通常按如下方式完成
letter = ((unsigned char)letter >> 1) | (letter << 7);
正如 Mark 在评论中指出的那样,您可以使用 OR |
或 XOR ^
。
关于c++ - 用换行位移动一个字符? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15648116/