How can i convert a QByteArray into a hex string?

僤鯓⒐⒋嵵緔 提交于 2020-04-11 04:42:59

问题


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?


回答1:


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.




回答2:


QString has following contructor:

constructor QString(const QByteArray &ba)

But note that an octal number is preceeded by 0 in c++, so some of your values are deciamal, some octal, none of them are hex.



来源:https://stackoverflow.com/questions/36603001/how-can-i-convert-a-qbytearray-into-a-hex-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!