我有一個的QString:字符串爲十六進制分裂
QString str = "1000140035";
我想從上面這樣的字符串中提取每個字節: -
Unsigned char a = 0x10
Unsigned char b = 0x00
Unsigned char c = 0x14
Unsigned char d = 0x00
Unsigned char e = 0x35
請建議如何做到這一點?嘗試但失敗了很多次。
我有一個的QString:字符串爲十六進制分裂
QString str = "1000140035";
我想從上面這樣的字符串中提取每個字節: -
Unsigned char a = 0x10
Unsigned char b = 0x00
Unsigned char c = 0x14
Unsigned char d = 0x00
Unsigned char e = 0x35
請建議如何做到這一點?嘗試但失敗了很多次。
QByteArray::fromHex
+ QString::toLatin1()
const QString str = "1000140035";
const QByteArray data = QByteArray::fromHex(str.toLatin1());
unsigned char a = data[0];
unsigned char b = data[1];
unsigned char c = data[2];
unsigned char d = data[3];
unsigned char e = data[4];
也許這是你在找什麼?該代碼將解析任意長度的十六進制字符串並返回一個2位十六進制數字及其數量的數組。它爲結果分配內存,所以你有責任在之後釋放它。提取的數字的數量通過第三個參數返回。
#include <QString>
#include <cmath>
unsigned HexToNum(char c)
{
if(c >= '0' && c <= '9')
return c - '0';
if(c >= 'A' && c <= 'F')
return 15 + c - 'A';
if(c >= 'a' && c <= 'f')
return 15 + c - 'a';
//Non hex char passed, return 0
return 0;
}
void ExtractBytes(const QString& hexString, unsigned char*& result, int& resultNumbersCount)
{
resultNumbersCount = static_cast<int>(ceil(hexString.length()/2));
result = new unsigned char[resultNumbersCount];
int i, j = -1;
for(i = 0; i < resultNumbersCount; ++i)
result[i] = 0;
for(i = 0; i < hexString.length(); ++i)
{
if(i % 2 == 0)
++j;
result[j] = result[j] * 16 + HexToNum(hexString.at(i).toLatin1());
}
}
您可以使用QString::toInt
和基礎設置爲16至十六進制字符串轉換爲int(或QString::toUInt
)。
QString str = "1000140035";
while(!str.isEmpty())
{
unsigned char byte = str.left(2).toInt(0, 16);
// do something with byte, store it somewhere or whatever...
str.remove(0, 2);
}
它總是更好地展示一個嘗試(http://stackoverflow.com/help/how-to-ask) – bibi