Unsolved to compare QByteArray and hexadecimal value
-
Hello everyone.
For a electronic application, i concieved an IHM which exchanges information with microcontroller.
I use the library QSerialport to send and receive information.That is my reception function:
void MainWindow::readData() { QByteArray data = serial.readAll(); buffer.append(data); if(data.at(1)==0x87) { cout<<"Détection du ping " <<endl; // ui->lineEdit_PingAnswer->setText(data.toStdString()); ui->lineEdit_Device->setText("Device STHC1 Detected"); } }
When i send the byte 0x0087, data is : "\000\207"
data[0] : 0 '\0'
data[1] : (hex) 87 / (hex) 87I want to compare if data(1) ==0x87 but it never enters in the if loop.
Thanks to spend time on my question.
Regards,
-
-
Hi,
QByteArray::at returns a char. You should rather test:
if (data.at(1) == '\x87')
-
@SGaist warning: comparison is always false due to limited range of data type [-Wtype-limits]
-
Thanks for the quick answer.
The cast (char) works :).I want also to create a string with 2 chars (data(0) and data(1) to fill the lineEdit_PingAnswer:
'''
ui->lineEdit_PingAnswer->setText(data........toStdString());
'''But it's impossible to use .toStdString with data.at(1).
I have to build the string manually ?
-
@SGaist Sorry my mistake, your version works as well
-
@Selim How do you want to interpret the bytes? Do you want to show '0' for the first byte in the string and "87" or "0x87" for the second?
-
I want to display the two bytes (it's the PING_ID) like:
in hexadecimal : 0x0087
Or better :
0000'0000'1000'0111' -
@Selim For hex you can do it like this:
QString str("0x0"); str.append(QString::number(array.at(0))); str.append(QString::number((uchar)array.at(1), 16));
-
Thanks, it's work wery well.
I will try to find function which translate u16 into binary form.Thanks a lot for your help !
-
@Selim Just do:
str.append(QString::number(array.at(0), 2)); str.append(QString::number((uchar)array.at(1), 2));
The only issue is: the first 0 byte isn't filled with 0
-
Thanks again ^^
Yes, i try and display the first 0 eight times