简体   繁体   English

如何将小端格式的 QByteArray 转换为无符号长整数

[英]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 有 4 个小端格式的值

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

to convert ba to big endian I do the following :要将 ba 转换为大端,我执行以下操作:

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:要将大端数组转换为 unsigned long,我尝试了以下操作:

baBigEndian.toULong(&ok,10);

The little endian byte array is correctly converted to big endian but the .toULong returns 0 in stead of 508632251.小端字节数组正确转换为大端,但 .toULong 返回 0 而不是 508632251。

How can I convert the baBigEndian array to an unsigned long?如何将 baBigEndian 数组转换为无符号长整数? 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). toULong()将不起作用,因为它期望 QByteArray 包含 ASCII 格式的数字的字符串表示(例如"0xbb1c511e" ,即 10 个 ASCII 字节),而您的 QByteArray 包含文字二进制字节(例如0xbb1c511e ,这是 4 个二进制字节)。

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:假设您的 QByteArray 包含大端格式的四个字节(就像您的示例代码中的第 2 步之后那样),那么这将起作用:

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但是请注意sizeof(unsigned long)不能保证在所有平台上都是 4 个字节,所以你最好使用一个固定宽度的类型,它保证总是 4 个字节宽,例如

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

Try memcpy试试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).此外,它可以通过reinterpret_cast完成,但我不建议您使用reinterpret_cast因为我在arm处理器上遇到了一些问题(而在x86它工作正常)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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