Important: Please read the Qt Code of Conduct -

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));

    link 1

  • @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 a QByteArray 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;

    fNum -78.98 array "-78.98"
    Float -78.98

    Details num-Qbytearray & Qbytearray-float

  • @anil_arise
    If he uses your QByteArray::number() approach, @stackprogramer should be aware that converts the number to a string representation in the QByteArray. And would need parsing to convert back to a number. Not what I would do for the original question/approach, but up to him.

Log in to reply