Please nominate your Qt Champions for 2021!

Appending a single byte to a QByteArray

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

    QByteArray bytes;

    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:


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


    but for that variant, I also get the warning

    warning C4309: 'static_cast': truncation of constant value

    I also tried


    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?

  • Moderators

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


    should serve you fine.

  • Thanks! While you were typing that, I also figured that out myself :-)
    See also

Log in to reply