对字符数组中的元素进行按位运算

Bitwise operations on elements from array of chars

我制作了一个十六进制数数组,我想将它们按位相加。在我的程序中,我想添加 0xFF 和 0x7F00。这是我的方法

#include <iostream>

using namespace std;

int main() {

    char data[2] = {0xFF, 0x7F};

    cout << (data[0] | (data[1] << 8)) << endl;

    system("pause");
    return 0;
}

我希望结果为 0x7FFF,十进制为 32767,但我得到 -1(十六进制为 0xFF)。

您遇到的问题源于两个事实:

  1. 两个操作数的bitwise operators requires integral promotion
  2. char 可以是有符号的也可以是无符号的

Promotion 会将较小类型的值(如 charshort)转换为 int,并且作为有符号值的一部分将进行符号扩展。如果 char 有符号,则值 0xff 将被转换为(32 位)int0xffffffff,即 -1.

无论您在按位或运算中使用什么值,结果仍然是 0xffffffff

简单的解决方案是显式使用 unsigned char(或者更好的 uint8_t)作为数组元素的类型:

uint8_t data[2] = {0xFF, 0x7F};