简体   繁体   中英

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

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!

toULong() won't work, since it expects the QByteArray to contain a string representation of the number in ASCII format (eg "0xbb1c511e" , which is 10 ASCII bytes), and your QByteArray contains the literal binary bytes instead (eg 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, eg

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM