2

I can initialize a QByteArray like:

QByteArray m_data;
m_data[0] = 0x0c;
m_data[1] = 0x06;
m_data[2] = 0x04;
m_data[3] = 0x04;
m_data[4] = 0x02;
m_data[5] = 0x00;

But I would like something more compact, like:

QByteArray m_data{0x0c, 0x06, 0x04, 0x04, 0x02, 0x00};

Unfortunately, this form isn't allowed:

error: could not convert '{12, 6, 4, 4, 2, 0}' from '<brace-enclosed initializer list>' to 'QByteArray'
     QByteArray m_data{0x0c, 0x06, 0x04, 0x04, 0x02, 0x00};
                                                          ^

Are there any alternatives (closer to my dream)?

(Does C++11/14/17 helps on this issue?)

KcFnMi
  • 5,516
  • 10
  • 62
  • 136
  • Do you need to store the `0x00` byte? Perhaps you could use the `QByteArray::QByteArray(const char * str)` constructor? – wally Nov 10 '16 at 18:53
  • Yes, I need all the Bytes there. – KcFnMi Nov 10 '16 at 18:57
  • 3
    `QByteArray m_data("\x0c\x06\x04\x04\x02", 6)` – Igor Tandetnik Nov 10 '16 at 19:33
  • https://stackoverflow.com/questions/36327327/is-there-a-shorter-way-to-initialize-a-qbytearray/36328073#36328073 – peppe Nov 11 '16 at 12:47
  • QByteArray *could* gain an constructor taking an initializer list, but I think that would not make your life easier. `{0x0c, 0x06, ...}` is a list of `int`s, not `char`s, and narrowing is forbidden in there => compile error. `{char(0x0c), char(0x06), ...}` would work, but that's a PAIN to write. Just use QByteArray(Literal) as suggested. – peppe Nov 11 '16 at 12:51

3 Answers3

2

You could let a template figure out how many elements are in the list:

using myarr = char[];

template <size_t N>
QByteArray make_QByteArray(const char(&a)[N]) {
    return {a,N};
}

Then create QByteArray with:

auto  m_data{make_QByteArray(myarr{0x0c, 0x06, 0x04, 0x04, 0x02, 0x00})};
wally
  • 10,717
  • 5
  • 39
  • 72
0

I was looking for such answer, but including declared variables into the expression; for instance:

char       v1 = 0x06, v2 = 0x04;
QByteArray m_data;

m_data[0] = 0x0c; m_data[1] =  v1 ; m_data[2] = v2 ;
m_data[3] =  v2 ; m_data[4] = 0x02; m_data[5] = 0x00;
//And a character higher than 0x7f
m_data[6] = 0x8b;

Here is a solution I've found:

char        v1 = 0x06, v2 = 0x04;
QByteArray  ba(std::begin<char>({0x0c, v1, v2, v2, 0x02, 0x00, '\x8b'}), 7);

Using std::begin or even std::initializer_list C++11 features this can be achieved.

delverdl
  • 85
  • 10
  • But then you have to manually count number of elements, which is error-prone and unmaintainable. – Ruslan Jul 28 '20 at 16:03
0

I am using:

QByteArray data(QByteArray::fromRawData("\x8B\x55\x0C\x83\xFA\x02\x75", 7));