It takes 4 bytes to represent an integer. How can I store an int in a QByteArray so that it only takes 4 bytes?
QByteArray::number(..)converts the integer to string thus taking up more than 4 bytes.QByteArray((const char*)&myInteger,sizeof(int))also doesn’t seem to work.
There are several ways to place an integer into a
QByteArray, but the following is usually the cleanest:This has the advantage of allowing you to write several integers (or other data types) to the byte array fairly conveniently. It also allows you to set the endianness of the data using
QDataStream::setByteOrder.Update
While the solution above will work, the method used by
QDataStreamto store integers can change in future versions of Qt. The simplest way to ensure that it always works is to explicitly set the version of the data format used byQDataStream:Alternately, you can avoid using
QDataStreamaltogether and use aQBuffer: