用换行移位字符?c++

Bit shifting a character with wrap? C++

本文关键字:c++ 字符 换行      更新时间:2023-10-16

我有一个二进制文件,它将作为字符读取。每个字符都被其他人向左移动了不知多少次(假设使用换行)。我希望能够读取每个字符,然后向右换行(我猜移位的次数必须手动计算,因为我还没有想出另一种方法)。

所以,我目前的想法是我读取一个字符,用temp创建一个副本,然后使用异或:

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 ^

语句temp <<= 7正在丢失您想要包装的位。你需要每次向左循环移动一位。首先检查最有效的char位,如果设置了,在进行移位之前将其移到最右边的位。

我倾向于使用更大的整型:

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

现在你只需要在val中移动值,而不需要任何额外的代码来将高位数包装回