Similar question however, I'm looking for a qt solution.
I'm looking for a way convert a 8 bit negative int into a hex representation. The example will explain it better.
qint8 width = - 100;
qDebug() << QString::number(width, 16);
// "ffffffffffffff9c"
The output is much more than 2 bytes.
However, when i change it to unsigned, it works fine.
quint8 width = - 100;
qDebug() << QString::number(width, 16);
// "9c"
The documentations states:
typedef quint8
Typedef for unsigned char. This type is guaranteed to be 8-bit on all platforms supported by Qt.
typedef qint8
Typedef for signed char. This type is guaranteed to be 8-bit on all platforms supported by Qt.
Shouldn't unsigned not be able to deal with negative numbers?
The problem is that QString::number
can accept int
or uint
types. It doesn't have versions for 8-bit integers, so they are implicitly casted to larger integers. It works fine with signed integer because leading zeros are removed.
You can however use QDataStream
, it provides operator <<
for large variety of types:
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::WriteOnly);
qint8 width = - 100;
stream << width;
qDebug() << buffer.toHex();
// output: "9c"