-2

I work with QT Creator (MinGW 5.3.0 C++, Windows) and want to write some serial-connection hex-data. I found a way but there is something wrong. Only one hex-data he convert wrong.

I hope my code will help to understand.

static const unsigned char mytestUC[] = {0x04,0x31,0xD2,0x01, 0xA1};
enum { NBYTES = sizeof(mytestUC) };
const char *mytest = reinterpret_cast<const char*>(mytestUC);
QByteArray testdata = QByteArray::fromRawData(mytest, sizeof(mytest)+1);
qDebug()<<"testdata "<<testdata;

I would think the output should be: testdata "\x04\31\xD2\x01\xA1"

But in real it looks like this: testdata "\x04""1\xD2\x01\xA1"

I tried some other way to write my hex-data directly in the QBytearray with append.

testdata .append((char) 0x04);
testdata .append((char) 0x31);
testdata .append((char) 0xD2);
testdata .append((char) 0x01);
testdata .append((char) 0xA1);

Why does the Programm convert only the the 0x31 in the wrong way and how can I make it better? Is there some easier way to write hex-data in QBytearray?

knowless
  • 13
  • 6

1 Answers1

0

Whe you print the QByteArray it tries to convert all characters to ASCII, but the numerical value is the 0x31. In serial port data is send in binary, so character '1' will be send as 0x31. To see data in hexa from a QByteArray you can use the function toHex(), example:

QByteArray ba;
ba.append((char) 0x31);
ba.append((char) 0x32);
ba.append((char) 0x33);
ba.append((char) 0x34);

qDebug() << "char: " << ba;
qDebug() << "hexa: " << ba.toHex();

The output will be:

char:  "1234" 
hexa:  "31323334" 

There is a function qint64 QIODevice::write(const QByteArray &byteArray) in QSerialPort class.

JMA
  • 494
  • 2
  • 13