PDA

View Full Version : reading integer with big/little endian



stef13013
2nd September 2012, 15:14
Hello,

I'm reading from a tcp server an integer (4-bytes) data
The tcp server is big endian

On my client, which is a little endian CPU, I've done this :


QTcpSocket sck;
qint32 v;

...
sck.read(data, 16);


#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
v = ntohl(*((qint32*) data));
#endif


Works pretty well, but sounds "old school". Do I have a better way to do that ?

Thanks...

yeye_olive
3rd September 2012, 22:28
Minor improvement: instead of those #if you could use Qt's conversion functions (http://qt-project.org/doc/qt-4.8/qtendian.html). You could even hide all of this in a simple function, e.g. qint32 readInt32(QTcpSocket *).

If the client and server are both Qt applications, and if you do not care about the details of the protocol they use to communicate, just use a QDataStream on top of the socket.