TheMeaningfulEngineer
TheMeaningfulEngineer

Reputation: 16359

Qt hex representation of a negative 8bit int?

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?

Upvotes: 0

Views: 1646

Answers (2)

ratchet freak
ratchet freak

Reputation: 48226

QString::number only takes ints and longs so both times width was promoted to a qint and quint resp

Unsigned promotion does not extend the sign bit while signed promotion does.

and documentation of QString::number says:

The base is 10 by default and must be between 2 and 36. For bases other than 10, n is treated as an unsigned integer.

that means the extended sign bits are displayed

Upvotes: 1

Pavel Strakhov
Pavel Strakhov

Reputation: 40512

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" 

Upvotes: 3

Related Questions