Search code examples
c++qtendiannessbit-shift

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


I'm reading a bytearray (2 byte big endian) with Qt

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

and want ot get int16. It works correctly but slow.

If I use

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

the result is wrong. The reason is the following:

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

Does someone know what I'm doing wrong?


Solution

  • Thxs to All!!!

    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());
    

    I tested it also for negativ values, as long they of course don't exceed the int limits.