Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorter way to initialize a QByteArray?

In my program I work a lot with serial communication so QByteArray is used very often.

I was wondering if there was a shorter way to initialize a QByteArray with specific bytes than:

const char test_data[] = {
    static_cast<char>(0xB1), static_cast<char>(0xB2),
    0x5, static_cast<char>(0xFF),
    static_cast<char>(0xEE), static_cast<char>(0xEE),
    static_cast<char>(0x0)}; // Note QByteArray should be able to hold 0 byte
const QCanBusFrame frame = QCanBusFrame(0xA1, QByteArray(test_data));

The static_cast<char> is necessary because otherwise C++11 gives an error about narrowing, because the range 0x7F to 0xFF is bigger than a char could fit--but a char is what the QByteArray constructor asks for.

This is the QByteArray constructor being used:

QByteArray::QByteArray(const char *data, int size = -1)

like image 391
DBedrenko Avatar asked Mar 31 '16 07:03

DBedrenko


1 Answers

Simple and effective:

QByteArray b = QByteArrayLiteral("\x12\x00\xa4\x42\x51\x00\x00\x99");
like image 100
peppe Avatar answered Sep 19 '22 22:09

peppe