How to convert float to Qbytearray in qt
-
Hi, I want to copy the value a float to QByteArray, I search and found these links.
but when I convert float to QByteArray, the negative float is converted to positive float... the sign number is wrong
How can convert float to QBytearray so that the positive/negative sign is not changed...Thanks in advance
readDataComplex.append(reinterpret_cast<const char*>(&commandOneFloat), sizeof(commandOneFloat)); readDataComplex.append(reinterpret_cast<const char*>(&commandTwoFloat), sizeof(commandTwoFloat));
-
Hi, I want to copy the value a float to QByteArray, I search and found these links.
but when I convert float to QByteArray, the negative float is converted to positive float... the sign number is wrong
How can convert float to QBytearray so that the positive/negative sign is not changed...Thanks in advance
readDataComplex.append(reinterpret_cast<const char*>(&commandOneFloat), sizeof(commandOneFloat)); readDataComplex.append(reinterpret_cast<const char*>(&commandTwoFloat), sizeof(commandTwoFloat));
@stackprogramer said in How to convert float to Qbytearray in qt:
the sign number is wrong
I don't know. But as per another thread recently discussed on this forum, you might try
QDataStream
to serialize/deserialize a float to/from aQByteArray
which I presume must get it right, if you cannot resolve your direct code approach. -
Try it simple:
float fNum = -78.98;
QByteArray array = QByteArray::number(fNum);
qDebug()<<"fNum "<<fNum <<"array"<<array;
float floatback = array.toFloat();
qDebug ()<<"Float "<<floatback;Output:
fNum -78.98 array "-78.98"
Float -78.98Details num-Qbytearray & Qbytearray-float
-
Try it simple:
float fNum = -78.98;
QByteArray array = QByteArray::number(fNum);
qDebug()<<"fNum "<<fNum <<"array"<<array;
float floatback = array.toFloat();
qDebug ()<<"Float "<<floatback;Output:
fNum -78.98 array "-78.98"
Float -78.98Details num-Qbytearray & Qbytearray-float
@anil_arise
If he uses yourQByteArray::number()
approach, @stackprogramer should be aware that converts the number to a string representation in theQByteArray
. And would need parsing to convert back to a number. Not what I would do for the original question/approach, but up to him.