c++qtendiannessqbytearrayulong

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!


Solution

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