How to input hex value to QByteArray efficient ?
-
Dear All,
I want to input hex value into QByteArray, below is my code:
QByteArray header; header = header.append(0x38); header = header.append(0x39); header = header.toHex();
As you see I have to input each value one by one, cannot direct input a series of number.
For example, I cannot define header[0x38,0x39,0x42,0x01,0xA8] in one code.
Is my above method correct ? Is there any better way to input hex data directly ?Thanks,
-
Dear @jsulm ,
It is not working in my project, I suspect my project is not C++ 11 ??
The error message is:no matching function for call to ‘QByteArray::QByteArray(<brace-enclosed initializer list>)’ QByteArray header{0x38,0x39,0x42,0x01,0xA8}; ^
My compiler is "~/rpi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/arm-linux-gnueabihf-g++". Is it support C++ 11 ?
Thanks,
-
C++11 you can do:
QByteArray header{0x38,0x39,0x42,0x01,0xA8};No, it's not working in C++14 either.
This seems to work:
unsigned char dat[]={0x38,0x39,0x42,0x01,0xA8}; QByteArray hex=QByteArray::fromRawData((char*)dat,5); qDebug()<<hex.toHex();
Annoying error with unsigned char, requiring a cast ...
(it's clearly explained in the doc, but they use const char that produce an error for me) -
You can also follow one of these three ways:
QByteArray ba1{"\x38\x39\x42\x01\xA8"}; QByteArray ba2 = QByteArrayLiteral("\x38\x39\x42\x01\xA8"); Stuff::ByteArray ba3{0x38,0x39,0x42,0x01,0xA8};
ba1
is constructed from a C-style string literal usingQByteArray::QByteArray(const char *data, int size = -1)
.ba2
is probably the most efficient, see QStringLiteral explained and Qt Weekly #13: QStringLiteral. Forba3
we use a small helper class that extendsQByteArray
:namespace Stuff { struct ByteArray: public QByteArray { ByteArray(std::initializer_list<unsigned char> lst) : QByteArray(reinterpret_cast<char const *>(lst.begin()), lst.size()) {} }; }
-
Thank you all.
if only add CONFIG += c++11:
QByteArray Testdate{0x41,0x42}; qDebug()<<"Testdata="<<Testdate; //then result is Testdata= "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
Use QList, QByteArray::fromRawData and @Wieland 's three approach could input hex value to QByteArray successfully.
I should try to understand what is C++11 and read Qt Weekly #13: QStringLiteral in more detail.
Thanks again.
-
@Hiloshi said in How to input hex value to QByteArray efficient ?:
QByteArray Testdate{0x41,0x42};
qDebug()<<"Testdata="<<Testdate;
//then result is
Testdata= "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"Because
QByteArray Testdate{0x41,0x42};
calls this constructor:QByteArray::QByteArray(int size, char ch)
with size=0x41=65 and ch=0x42='B'.See QByteArray Class:
Constructs a byte array of size size with every byte set to character ch.