为什么在 C++ big endian to int16 with bitshift 中不起作用?

Why does in C++ big endian to int16 with bitshift not work?

我正在用 Qt 读取字节数组(2 字节大端)

QByteArray a = data.mid(cellNumber, 2);
int16 res = qFromBigEndian<qint16>(a);

并希望获得 int16。它工作正常但速度慢。

如果我用

std::bitset<16> b0(a[0]);
std::bitset<16> b1(a[1]);
qint16 b = (b0 << 8) | (b1 << 0);

结果是错误的。原因如下:

00000001 a0
10101011 a1

00000000 00000001 b0 correct
11111111 10101011 b1 not correct, why does it fill with 1? (should be 00000000 10101011)
-----------------
11111111 10101011 wrong!
00000001 10101011 this would be correct

有人知道我做错了什么吗?

bitset 采取 unsigned long longQByteArray::operator[] return char, signed 在你的情况下。

而且你有积分提升,把负数当成大数(补1)

可能的解决方案

std::bitset<16> b0(static_cast<unsigned char>(a[0]));
std::bitset<16> b1(static_cast<unsigned char>(a[1]));

所有人的事情!!!

std::bitset<16> b0(static_cast<unsigned char>(a[cellNumber]));
std::bitset<16> b1(static_cast<unsigned char>(a[cellNumber + 1]));
std::bitset<16> resb = (b0 << 8) | (b1 << 0);
int16_t resi = int16_t(resb.to_ulong());

我也测试了它的负值,当然只要它们不超过 int 限制即可。