用换位移位字符? C ++ [英] Bit shifting a character with wrap? C++

查看:82
本文介绍了用换位移位字符? C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二进制文件,该文件将作为字符读取.每个字符被其他人向左移了未知的次数(假定为自动换行).我希望能够读入每个字符,然后将换档向右换行(我想必须手动找出要移动的次数,因为我还没有想出其他方式).

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

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

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;
}

这在我精疲力竭的头脑中是有道理的,但是它不起作用...而且我不知道为什么. char的大小为1个字节,所以我认为我只需要弄乱8位.

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.

任何帮助将不胜感激.

已解决.非常感谢大家.爱死这个社区,你们真棒!

推荐答案

请注意字符的签名.在许多系统上,它都是经过签名的.因此,您的letter >>= 1是填补这一转变的信号.

Pay attention to the signess of a char. On many systems it is signed. So your letter >>= 1 is sign filling the shift.

旋转整数通常如下进行

letter = ((unsigned char)letter >> 1) | (letter << 7);

正如Mark在注释中指出的那样,您可以使用OR |或XOR ^.

As Mark points out in the comments, you can use either OR | or XOR ^.

这篇关于用换位移位字符? C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆