B.K*_*.K. 6 c++ bit-manipulation bit-shift bit
我有一个二进制文件,将作为字符读入.其他人将每个角色移位到左侧未知次数(假设有包裹).我希望能够读入每个角色,然后将换档换到右侧(换档的次数我想必须手动计算出来,因为我还没想出另一种方法).
所以,我目前的想法是我读了一个字符,用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;
}
Run Code Online (Sandbox Code Playgroud)
这在我筋疲力尽的头脑中是有道理的,但它不起作用......我无法弄清楚为什么.char的大小是1个字节,所以我想我只需要乱用8位.
任何帮助,将不胜感激.
编辑:解决了.非常感谢大家.爱这个社区致死,你们真棒!
Kyu*_*rem 12
注意char的signess.在许多系统上都签了名.所以你letter >>= 1的标志是填补这一转变.
旋转整数通常如下进行
letter = ((unsigned char)letter >> 1) | (letter << 7);
Run Code Online (Sandbox Code Playgroud)
正如Mark在评论中指出的那样,您可以使用OR |或XOR ^.
| 归档时间: |
|
| 查看次数: |
6428 次 |
| 最近记录: |