c++ - 用换行位移动一个字符? C++

标签 c++ bit-manipulation bit bit-shift

我有一个二进制文件,将作为字符读入。每个字符都被其他人向左移动了未知次数(假设换行)。我希望能够读入每个字符,然后将 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/

相关文章:

c++ - '&' 在 C++ 声明中做了什么?

c - 如何将一个字节分成 4 对 2 位

c - 使用 C 中的位显示卡片的值

java 位运算符,abs 幂

c++ - 类内部 lambda 和 boost 函数

c++ - 检查 C++/C++11 中的输入缓冲区对齐 : what is the best way?

c++ - 谷歌测试 : "char-array initialized from wide string"

math - 为什么我们需要在做 2 的补码时加 1

java - 在 Android Java 中将位保存在字节流中?

c - 字符中的位运算