Float to Qbytearray in hex format



  • Hi,
    I am using qt 4.8.5.
    I would like to append 4byte float value to qbytearray.
    eg. float f = 32.6 (0x42026666)
    if qbytearray is 0x6537, i would like to append the float value in hex as well.
    i.e result = 0x653742026666

    i tried this but i didnt get the result that i expected.

    bytes.append(reinterpret_cast<const char*>(&f), sizeof(f));
    

    thanks in advance.


  • Moderators

    @sandycoolxyz said in Float to Qbytearray in hex format:

    if qbytearray is 0x6537, i would like to append the float value in hex as well.

    Not exactly clear what you mean here.
    Is this already stored as different characters '0', 'x', '6', '5', '3', '7' or is it a two byte bytearray of 0x65, 0x37?

    Note, "0x" is typically printed as addition for human interpretation. It is not typically expected to be part of QByteArray.



  • Hi @sandycoolxyz

    did you try it the same as with the integers already:

    union (
    int iValue;
    float fValue;
    };
    bytes.append(QByteArray::number(iValue,16)).rightJustified(8,'0');
    

    Of course, you should consider to use a more C++-like approach that works with all standard data types:

    QByteArray data;
    QDataStream io(&data,QIODevice::WriteOnly);
    io << fValue;
    

    -Michael.



  • @m-sue
    I used the union method. Works fine with the positive numbers.
    But if its negative value following gets appended ffffffffc201999a instead of c201999a



  • @m.sue said in Float to Qbytearray in hex format:

    int iValue;

    use quint32 iValue; instead


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.