'QByteArray from hex literal unicode characters

I see how a QByteArray to convert to and from Ascii character I see how to convert a QString to utf-8 using QString::toUtf8()

However, I do not see how to initialize a QByteArray with hex literals containing unicode characters. The unicode characters are too large to fit into a char. They will however fit into an unsigned char.

If I run the following code:

QString test = "¢";
QByteArray utf8bytes = test.toUtf8();

My debugger says:

utf8bytes = { (char)-62 '\302', (char)-94 '\242' }

Whatever that means...

What I ultimately want to accomplish is to be able to provide test data in the following unit test code:

void stomp_frame_tests::test_nonAsciiCharactersInHeaderKey()
{
    /* Frame we are testing with:
    SEND
    Bad¢Character:Erroneus
    destination:/queue/a
    content-type:text/json;charset=utf-8
    content-length:22

    This is a test message
    */

    const char data[]   = {0x53, 0x45, 0x4e, 0x44, 0x0a, 0x42, 0x61, 0x64, 0xc2, 0xa2, 0x43, 0x68, 0x61, 0x72, 0x61,
                          0x63, 0x74, 0x65, 0x72, 0x3a, 0x45, 0x72, 0x72, 0x6f, 0x6e, 0x65, 0x75, 0x73, 0x0a, 0x64,
                          0x65, 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x2f, 0x71, 0x75, 0x65,
                          0x75, 0x65, 0x2f, 0x61, 0x0a, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x74, 0x79,
                          0x70, 0x65, 0x3a, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x6a, 0x73, 0x6f, 0x6e, 0x3b, 0x63, 0x68,
                          0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, 0x75, 0x74, 0x66, 0x2d, 0x38, 0x0a, 0x63, 0x6f, 0x6e,
                          0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x3a, 0x32, 0x32, 0x0a,
                          0x0a, 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, 0x74, 0x65, 0x73, 0x74,
                          0x20, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x00};
    auto testData = QByteArray::fromRawData(data, sizeof(data));
}

This fails, of course, because 0xc2 and 0xa2 are too large to fit into a char. How would you go about initializing the QByteArray with the appropriate data?

qt


Solution 1:[1]

Perhaps you are looking for QByteArrayLiteral:

auto byteArray = QByteArrayLiteral("\x01\x02\x03\x04\x05");

QByteArrayLiteral Documentation

Solution 2:[2]

Use QByteArray::fromHex instead:

auto testData = QByteArray::fromHex("C2A2");

Document: https://doc.qt.io/qt-5/qbytearray.html#fromHex

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ManuelH
Solution 2 mengkun