Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Appending a single byte to a QByteArray



  • I'm trying to append the byte 0x89 (10001001) to a QByteArray as follows:

    QByteArray bytes;
    bytes.append(0x89);
    

    However, this gives me the following warning:

    warning C4309: 'argument': truncation of constant value
    

    I understand the reason for this, namely that 0x89 is of type int, while QByteArray::append() expects a parameter of type char, so the 0x89 int value is truncated to char, which is dangerous.

    I am now wondering what is the clean way to solve this warning. The following works and does not give me a warning:

    bytes.append(char(0x89));
    

    but I don't like that solution because it uses old-style C-casts. I therefore tried:

    bytes.append(static_cast<char>(0x89));
    

    but for that variant, I also get the warning

    warning C4309: 'static_cast': truncation of constant value
    

    I also tried

    bytes.append(QByteArray::number(0x89));
    

    but that variant doesn't seem to insert the correct byte in my bytearray. If I print it using

    qDebug() << bytes.toHex();
    

    I get "313337" instead of "89".

    So what is the correct, most elegant and portable way to put 0x89 (10001001) into my QByteArray and avoid the warning?


  • Qt Champions 2017

    @Bart_Vandewoestyne said in Appending a single byte to a QByteArray:

    bytes.append('\x89');
    

    should serve you fine.



  • Thanks! While you were typing that, I also figured that out myself :-)
    See also http://en.cppreference.com/w/c/language/character_constant
    Thanks!


Log in to reply