Mr. Developer
Mr. Developer

Reputation: 3417

Insert Byte inside QByteArray from QString - Qt C++

I've little problem, I need to send trought modbus some bytes. One from some, is: 0x04, and 0xFB

QString first, second;
first = "0x04";
second = "0xFB"

QByteArray array;
array[0] = first;
array[1] = second;
ecc...ecc..

Ho to solve ? I've tryed this:

array[0] = first.toUInt(nullptr,16);

but this last convert hex in other value. How to solve ?

Upvotes: 1

Views: 2494

Answers (2)

Luis Lourenço
Luis Lourenço

Reputation: 37

You can do convert the bytes directly to hex code and append it to the final bytearray like this:

QByteArray array;
array.append(QByteArray::fromHex("04"));
array.append(QByteArray::fromHex("FB"));

Or simply:

QByteArray array = QByteArray::fromHex("04FB");

Upvotes: 2

IlBeldus
IlBeldus

Reputation: 1040

you can use:

QByteArray array=first.toLatin1() + second.toLatin1();
array.replace("0x","");
array= QByteArray::fromHex(array);

Upvotes: 1

Related Questions