问题描述
我有 QByteArray 的打击.
I have the blow QByteArray.
QByteArray ba;
ba[0] = 0x01;
ba[1] = 0x10;
ba[2] = 0x00;
ba[3] = 0x07;
我真的不知道如何将这个 QByteArray 转换为具有01100007"的结果字符串,我会使用 QRegExp 对这个字符串进行模式匹配?
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?
推荐答案
首先,QByteArray
不包含十六进制值",它包含字节(顾名思义).数字只有在打印为文本时才能为十六进制".
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.
您的代码应该是:
QByteArray ba(4, 0); // array length 4, filled with 0
ba[0] = 0x01;
ba[1] = 0x10;
ba[2] = 0x00;
ba[3] = 0x07;
无论如何,要将 QByteArray
转换为十六进制字符串,您很幸运:只需使用 QByteArray::toHex()
方法!
Anyway, to convert a QByteArray
to a hex string, you got lucky: just use QByteArray::toHex()
method!
QByteArray ba_as_hex_string = ba.toHex();
请注意,它返回 8 位文本,但您可以将其分配给 QString
而不必担心编码,因为它是纯 ASCII.如果您想在十六进制数字中使用大写 AF 而不是默认的 af,您可以使用 QByteArray::toUpper()
转换大小写.
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.
这篇关于如何将 QByteArray 转换为十六进制字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!