Appending a single byte to a QByteArray
-
I'm trying to append the byte 0x89 (10001001) to a
QByteArrayas follows:QByteArray bytes; bytes.append(0x89);However, this gives me the following warning:
warning C4309: 'argument': truncation of constant valueI understand the reason for this, namely that 0x89 is of type
int, whileQByteArray::append()expects a parameter of typechar, so the 0x89intvalue is truncated tochar, 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 valueI 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?
-
I'm trying to append the byte 0x89 (10001001) to a
QByteArrayas follows:QByteArray bytes; bytes.append(0x89);However, this gives me the following warning:
warning C4309: 'argument': truncation of constant valueI understand the reason for this, namely that 0x89 is of type
int, whileQByteArray::append()expects a parameter of typechar, so the 0x89intvalue is truncated tochar, 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 valueI 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?
@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!