Is there a shorter way to initialize a QByteArray?

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

I was wondering if there was a shorter way to initialize a QByteArray 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)); 

static_cast<char> necessary because otherwise C ++ 11 gives a narrowing error because the range from 0x7F to 0xFF is greater than a char can match - but a char is what the QByteArray constructor asks.

The constructor of QByteArray :

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

+6
source share
6 answers

Being inspired by the answers above, this is what I finally came up with:

 const quint8 testData[] {0xB1, 0x00, 0xB2, 0x00}; const QCanBusFrame cFrame = QCanBusFrame( 0xA1, QByteArray(reinterpret_cast<const char*>(testData), sizeof(testData))); 

I prefer to have bytes as byte numbers rather than alphabetic characters when working with serial communication.

After a discussion in ## C ++, I was informed that reinterpret_cast properly used in this situation.

+2
source

Simple and effective:

 QByteArray b = QByteArrayLiteral("\x12\x00\xa4\x42\x51\x00\x00\x99"); 
+17
source

like this:

 const unsigned char str[] = {0xff, 0xed, 0xba, 0xd1}; QByteArray ba(reinterpret_cast<const char*>(&str[0]),std::extent<decltype(str)>::value); 

the QByteArray constructor now looks weird, but the byte sequences are clear. You can also add a trailing 0-byte array instead of using std::extent , but in general you can have zero bytes in the middle of the sequence.

+2
source

As an alternative to QByteArrayLiteral you can flip your own if you want:

 #include <QByteArray> template <int N> QByteArray arrayFromLiteral(const char (&data)[N]) { return QByteArray::fromRawData(data, N-1); } int main() { const auto arr = arrayFromLiteral("\xB1\xB2\0\1"); Q_ASSERT(arr.size() == 4); Q_ASSERT(arr[0] == (char)0xB1); Q_ASSERT(arr[1] == (char)0xB2); Q_ASSERT(arr[2] == (char)0x00); Q_ASSERT(arr[3] == (char)0x01); } 
+2
source

May work slowly:

 QByteArray ba = QByteArray::fromHex(QVariant("B1B2FFEEEE00").toByteArray()); 
+1
source

Have you tried the following:

 const unsigned 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>(0xB3)}; const QCanBusFrame frame = QCanBusFrame(0xA1, QByteArray((char*)test_data)); 

You use the constructor: QByteArray::QByteArray(const char *data, int size = -1) .

If the size is negative, it is assumed that the data points to a zero-terminated string, and its length is determined dynamically. The trailing null character is not considered part of the byte array.

0
source

All Articles