字符串到十六进制拆分

时间:2016-02-18 10:53:23

标签: qt qstring

我有一个QString:

QString str = "1000140035";

我想从上面的字符串中提取每个字节,如下所示: -

Unsigned char a = 0x10
Unsigned char b = 0x00
Unsigned char c = 0x14
Unsigned char d = 0x00
Unsigned char e = 0x35

请建议如何执行此操作...已尝试但多次失败。

3 个答案:

答案 0 :(得分:3)

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];

答案 1 :(得分:1)

也许这就是你要找的东西?代码将解析任意长度的十六进制字符串,并返回一个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());
    }
}

答案 2 :(得分:1)

您可以使用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);
}