简体   繁体   English

用包裹移位一个字符? C ++

[英]Bit shifting a character with wrap? 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). 我希望能够读入每个角色,然后将换档换到右侧(换档的次数我想必须手动计算出来,因为我还没想出另一种方法)。

So, my current idea is that I read in a character, create a copy with temp and then use XOR: 所以,我目前的想法是我读了一个字符,用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;
}

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. char的大小是1个字节,所以我想我只需要乱用8位。

Any help would be appreciated. 任何帮助,将不胜感激。

EDIT: Solved. 编辑:解决了。 Thanks so much to everyone. 非常感谢大家。 Love this community to death, you guys are awesome! 爱这个社区致死,你们真棒!

Pay attention to the signess of a char. 注意char的signess。 On many systems it is signed. 在许多系统上都签了名。 So your letter >>= 1 is sign filling the shift. 所以你的letter >>= 1是填补班次的标志。

Rotating integers is usually done as follows 旋转整数通常如下进行

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

As Mark points out in the comments, you can use either OR | 正如Mark在评论中指出的那样,你可以使用OR | or XOR ^ . 或XOR ^

The statement temp <<= 7 is losing the bits that you want to wrap. 语句temp <<= 7正在丢失要包装的位。 You will need to loop shifting left one bit at a time. 您需要一次循环向左移位一位。 First checking the most significant char bit and if set moving it to the right most bit before doing the shift. 首先检查最重要的char位,如果设置将其移动到最右位,然后再进行移位。

I'd be inclined to use a larger integral type: 我倾向于使用更大的整数类型:

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

Now you just have to shift values in val , without any additional code to wrap the high bits back in. 现在你只需要在val移位值,而无需任何额外的代码来重新包装高位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM