Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i convert a QByteArray into a hex string?

Tags:

qt

qt5

I have the blow QByteArray.

QByteArray ba;
ba[0] = 0x01;
ba[1] = 0x10;
ba[2] = 0x00;
ba[3] = 0x07;

I have really no idea how to convert this QByteArray into resulted string which have "01100007", which i would use the QRegExp for pattern matching on this string?

like image 474
DrunkenMaster Avatar asked Apr 13 '16 15:04

DrunkenMaster


1 Answers

First of all, the QByteArray does not contain "hex values", it contains bytes (as it's name implies). Number can be "hex" only when it is printed as text.

Your code should be:

QByteArray ba(4, 0); // array length 4, filled with 0
ba[0] = 0x01;
ba[1] = 0x10;
ba[2] = 0x00;
ba[3] = 0x07;

Anyway, to convert a QByteArray to a hex string, you got lucky: just use QByteArray::toHex() method!

QByteArray ba_as_hex_string = ba.toHex();

Note that it returns 8-bit text, but you can just assign it to a QString without worrying much about encodings, since it is pure ASCII. If you want upper case A-F in your hexadecimal numbers instead of the default a-f, you can use QByteArray::toUpper() to convert the case.

like image 97
hyde Avatar answered Sep 22 '22 23:09

hyde