PDA

View Full Version : Qt-- Way of reading and writing bytes (4 bytes and 8 bytes)



ehnuh
22nd October 2012, 14:55
Hi, i am currently creating a project that makes use of binary files containing char, ulong and ulonglong datatypes. Opening the file and storing it on a pointer is no problem in Qt for I just use QFile.

The problem arises when I try to display data of type ulong and ulonglong. Qt reads its from the least significant bit to the most significant bit.

So for example i will have to read a ulong long datatype:
(hex) 00 00 00 00 3e 80 00 00 1048576000(in decimal)

..when I view the data in memory editor, it appears ok but when I use it to populate my struct, it reads in reverse. My text box displays 80 3e 00 00 00 00.

Can anyone enlighten me?

thanks!

Lesiok
22nd October 2012, 16:28
Did You know what it is big endian and little endian ?

ChrisW67
23rd October 2012, 01:08
Qt reads bytes from a file in precisely the order they are in the file. If you a reading 4/8 bytes into a patch of memory and not allowing for byte order differences between the file order and your machine's int/long long order then you end up with int/longlong values that don't reflect what you expect.

The file is in big-endian format (AKA network order) if the bytes are in the order you list. Your processor is most likely little endian (e.g. Intel x86 processors). The first byte in the file (00), the most significant byte from the sender's point of view, ends up in the first byte of the memory set aside for your long long. Your processor treats this as the least-significant byte of the long long.

The functions ntohs() and ntohl() do byte swapping from network to host order for 16- and 32-bit values respectively. See http://stackoverflow.com/questions/809902/64-bit-ntohl-in-c for 64-bit options.

With care you could use QDataStream to read the file and handle the swapping for you.

ehnuh
23rd October 2012, 08:58
thank you very much for the replies!

wysota
23rd October 2012, 09:40
The functions ntohs() and ntohl() do byte swapping from network to host order for 16- and 32-bit values respectively.
There are also qFromBigEndian() and qFromLittleEndian() (and their "to" equivalents) template functions in Qt.