简体   繁体   中英

Convert QByteArray to unsigned short: not as expected

I have a QByteArray like this:

QByteArray idx0;

// idx0 is then assigned 4 bytes,
// idx0 content is shown on debugger as:

// idx0 "\000\000\001\000"  QByteArray
//          '\0'    0       0x00    char
//          '\0'    0       0x00    char
//                  1       0x01    char
//          '\0'    0       0x00    char

I convert the QbyteArray to unsigned short like this:

unsigned short ushortIdx0;
if ( idx0.size() >= sizeof(ushortIdx0) ) {
    ushortIdx0 = *reinterpret_cast<const unsigned short *>( idx0.data() );
}

The Debugger shows ushortIdx0 value as 0 :

// Debugger shows:
//
// ushortIdx0   0   unsigned short

However , when I convert the Little Endian value of 0x 00 00 01 00 to UINT32 - Little Endian by this website , I get:

UINT32 - Little Endian (DCBA):

Raw             UINT32
00 01 00 00     65536

Why the result of that website is different from what I get by my code? I don't get it. I appreciate any help.

As per the comment you can't always assume unsigned short is a certain size. If you know that you need an unsigned integer with a certain number of bits then use the appropriate type from cstdint -- uint32_t in this case.

With regard to endian issues, since you're using Qt why not use QDataStream to serialize/deserialize data in a platform agnostic manner. Write an unsigned 32 bit integer using...

quint32 data = ...;
QByteArray ba;
QDataStream ds(&ba, QIODevice::ReadWrite);
ds << data;

And similarly to read the data back.

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