Thanush Ganesh
Thanush Ganesh

Reputation: 23

How to convert a QString containing a hex value to an uint?

QString samp_buff[100];
QByteArray data;
uint8_t speed;

samp_buff[3] = data.toHex(); //I converted the QByteArray into a string
qDebug() << "read_every_data_"<< samp_buff[3];

speed = samp_buff[3].toUInt(); //Trying to convert the string to uint8_t
qDebug() << "Converted to UINT8" << speed;

Hi! I successfully got the Qbytearray value (data) stored in as a QString in the samp_buff array of strings, and also during the conversion of QString to uint8_t in the form of hex.

Data:  "\x07"       //QByteArray
read_every_data_ "07"    //QString
Converted to UINT8 7    //Uint8_t

Its working fine for this but the problem arises when this happens.

Data:  "\x0B"       //QByteArray
read_every_data_ "0b"    //QString
Converted to UINT8 0     //Uint8_t

Whenever the hex string has alphabets in it, the result of the conversion becomes zero.

Upvotes: 1

Views: 1027

Answers (1)

kotatsuyaki
kotatsuyaki

Reputation: 1641

As the documentation of QString::toUint suggests, the signature of the function looks like this.

uint QString::toUInt(bool *ok = nullptr, int base = 10) const

The second argument base is for specifying the base. To convert from hex strings, supply 16 to it.

speed = samp_buff[3].toUInt(nullptr, 16);

Upvotes: 2

Related Questions