2

I need to be able to convert a QString in this format: "0x00 0x00 0x00 0x00"

To a byte array like this:

0x00,
0x00,
0x00,
0x00

I was able to do this in Visual Studio / C# like this:

byte[] bytes = string.Split(' ').Select(s => Convert.ToByte(s, 16)).ToArray();

However I am now using Qt / C++ and I need a way to do the same thing. What would be the easiest way to do this?

0

1 Answer 1

5

Not the most concise solution, but at least safe, I guess (invalid values are not appended):

QString string = "0x00 0x00 0x00 0x00";
QByteArray bytes;

for(auto const& x : string.split(' '))
{
    bool ok;
    uint val = x.toUInt(&ok, 16);

    if(ok && val <= 0xff)
        bytes.append(static_cast<char>(val));
}

This might be faster (invalid values are left equal to 0):

QString string = "0x00 0x00 0x00 0x00";
QStringList list = string.split(' ');
QByteArray bytes(list.size(), '\0');

for(size_t i = 0; i < list.size(); ++i)
{
    bool ok;
    uint val = list[i].toUInt(&ok, 16);

    if(ok && val <= 0xff)
        bytes[i] = static_cast<char>(val);
}

You can omit the check in both cases, if all you want is speed.

Sign up to request clarification or add additional context in comments.

2 Comments

Your second option will be faster but initialising the byte array is wasteful since all bytes will be set in the for loop anyway.
There's if, they might not. The point of the second snippet is that there's no reallocation of the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.