Reputation: 7962
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 as0
:
// 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.
Upvotes: 2
Views: 1302
Reputation: 12899
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.
Upvotes: 2