QByteArray array;
union {
char bytes[sizeof(float)];
float value;
} myFloat;
for (int i = 0; i < 10; i++) {
myFloat.value = 2.3 + i;
array.append(myFloat.bytes);
qDebug() << array.length(); //9, 18, 27, etc, instead of 4, 8, 12, etc?
}
Hey, I'm trying to construct a QByteArray to store and send via TCP at a later stage, via QTcpSocket::write(QByteArray);
. However, the length increase of the array was not what I expected, and when I send it via Tcp, my readHandler seems to start reading gibberish after the first float. This seems to be solved by using another append function array.append(float.bytes, sizeof(float));
. Does anyone know:
- What went wrong in the first place? Why does adding a 4 byte char result in a 9 bytes longer QByteArray? Has it to do with the
\o
's being added? - Will
array.append(float.bytes, sizeof(float));
method work? Meaning, if I send the array, will I send 10*4 bytes of raw float values?
The
append()
overload you (unintentionally) picked treats the passed argument as a zero-terminated string. Obviously, thefloat
value seems to contain a zero byte at some point so theappend()
function eventually stops reading.To append binary data, I'd use
QByteArray::fromRawData()
to obtain aQByteArray
and then append it:This makes your intention clear and it avoids the
union
trick, which is undefined behaviour anyway.