为什么在C ++ big endian中使用带位移的int16不起作用?

问题描述 投票:1回答:2

我正在用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

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

c++ qt endianness bit-shift
2个回答
1
投票

[bitsetunsigned long long,而QByteArray::operator[]返回char,在您的情况下为signed

并且您有一个完整的提升,将负数设为大数(填充1)。

可能的解决方案

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

0
投票

感谢所有人!

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限制。

© www.soinside.com 2019 - 2024. All rights reserved.