How to convert a QByteArray in little endian format to a unsigned long

941 Views Asked by At

I have a QByteArray with 4 values in little endian format

QByteArray ba;
ba.append(0xbb);
ba.append(0x1c);
ba.append(0x51);
ba.append(0x1e);

to convert ba to big endian I do the following :

baBigEndian[0] = ba[3];
baBigEndian[1] = ba[2];
baBigEndian[2] = ba[1];
baBigEndian[3] = ba[0];

to convert the big endian array to an unsigned long i tried the following:

baBigEndian.toULong(&ok,10);

The little endian byte array is correctly converted to big endian but the .toULong returns 0 in stead of 508632251.

How can I convert the baBigEndian array to an unsigned long? Or is there a way to directly convert from a little endian array to an unsigned long?

Thanks in advance!

2

There are 2 best solutions below

3
On BEST ANSWER

Try memcpy

quint32 value = 0; //or qint32
memcpy(&value, baBigEndian.data(), sizeof(quint32));//or baBigEndian instead baBigEndian.data() if you use plain array instead QByteArray

Also, it can be done with reinterpret_cast but I do not recommend you to use reinterpret_cast because I had some problems on arm processors (while on x86 it works fine).

1
On

toULong() won't work, since it expects the QByteArray to contain a string representation of the number in ASCII format (e.g. "0xbb1c511e", which is 10 ASCII bytes), and your QByteArray contains the literal binary bytes instead (e.g. 0xbb1c511e, which is 4 binary bytes).

Assuming your QByteArray contains the four bytes in big-endian format (as it does after step 2 in your example code), then this would work:

unsigned long val = ntohl(*((const unsigned long *)ba.data()));

Note however that sizeof(unsigned long) is not guaranteed to be 4 bytes on all platforms, so you'd be better off using a fixed-width type that is guaranteed to always be 4 bytes wide instead, e.g.

quint32 val = ntohl(*((const quint32 *)ba.data()));