用换行移位字符?c++
Bit shifting a character with wrap? C++
我有一个二进制文件,它将作为字符读取。每个字符都被其他人向左移动了不知多少次(假设使用换行)。我希望能够读取每个字符,然后向右换行(我猜移位的次数必须手动计算,因为我还没有想出另一种方法)。
所以,我目前的想法是我读取一个字符,用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
中移动值,而不需要任何额外的代码来将高位数包装回
相关文章:
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 指向指向字符数组的指针数组的指针
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 比较字符数组
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++中无符号字符溢出
- 使用无符号字符数组有效存储内存