Get a string representation of a single byte from QByteArray? - qt

I have a QByteArray i create manually:
QByteArray hexArray(QByteArray::fromHex("495676"));
If this was encoded ASCII it would be "IVv".
If I want to get a single byte of data from that array.
I can do that like this:
qDebug() << messageToBeSent_raw[0];
However, that outputs I, which is correct but I would like to get 49. What I'm looking for is an equivalent of the QByteArray::toHex() just for a single byte. Is there a way to do it?

You can use QString::number.
qDebug() << QString::number(hexArray[0], 16);

Related

Construct a QByteArray from a HEX value entered as a QString

If QString str = "0xFFFF", how to turn this text representation of an hex into a QByteArray? In the end, I would like to have the same of what I get from the following:
QByteArray ba;
ba.resize(2);
ba[0] = 0xFF;
ba[1] = 0xFF;
In either case the final QByteArray would be a sequence of hex values, i.e. FFFF. Conversion should be applied on that string. Given that, if your input string is provided prepended with the 0x, you should get rid of it via mid().
Here is a code snippet which compares the results of the two approaches: manually filling the QByteArray with hex values or converting hex values from a QString:
QByteArray array1;
array1.resize(2);
array1[0] = 0xFF;
array1[1] = 0xFF;
QString str = "0xFFFF";
QString value = str.mid(2); // "FFFF" <- just the hex values!
QByteArray array2 = QByteArray::fromHex(value.toLatin1());
qDebug() << array1; // not printable chars
qDebug() << array2;
qDebug() << array1.toHex(); // to have a printable form use "toHex()"!
qDebug() << array2.toHex();

Compare raw hexadecimal values in Qt?

Below a QbyteArray is created and it contains a byte with the hexadecimal value 49. 49 is one byte of data written in memory, it isn't an ASCII string representation of 49 (which is 2 bytes)
QByteArray data(QByteArray::fromHex("49"));
At some point I populate the data with additional bytes.
data.append(QByteArray::fromHex("7656"))
How to compare a single byte with a hex value?
Example:
This passes (49 hex is 73 decimal):
if (data.at(0) == 73)
qDebug() << "True"
But i need to work with hex values:
if (data.at(0) == WHAT_HERE?("49"))
qDebug() << "True"
In C/C++, a hexadecimal integer literal is prefixed with 0x. So:
if (data.at(0) == 0x49)
qDebug() << "true";
if you know it at compile time then you can do 0x49
if you get a QString to compare it with then
QString test="47";
bool ok;
int result = test.toInt(&ok,16);
if(ok && data.at(0)==result){
//they are equal
}

Serial port communication in Qt

I am new to Qt and need to prepare a project to send hex commands from rs232.
QString line contains 64bit binary data which i have to convert into hexadecimal and send it through rs232 .
QString a=ui->comboBox->currentText();
QString s1;
s1="./calc "+a;
QProcess p1;
p1.start(s1);
p1.waitForFinished(-1);
QString line ;
//read
QFile file("TeleOutput.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream in (&file);
line = in.readAll();
ui->plainTextEdit->setPlainText(line);
So, how to convert 64 bit binary data in QString line to hexadecimal value and transfer it through rs232?
First of all - you should really use QtSerialPort
Second of all - QString is a class, which works with actual string. QByteArray works with raw data. When you write QString line = in.readAll(); it implicitly calls QString(const QByteArray &ba), which uses QString::fromAscii.
Last of all, if you want to process 64bit integers, you should do something like this:
quint64 d;
QDataStream stream(&file);
while (!stream.atEnd())
{
stream >> d;
process(d);
}
Update
Quote:
My problem is that in plainTextEdit
"1111110101000101010101010101010101010101010101010101010......." 64
bit data is populated , i need to convert this data into hex and send it through rs232
Solution:
QString binData = plainTextEdit.toPlainText();
QByteArray result;
while (binData.size() >= 64)
{
quint64 d;
QString dataPiece = binData.left(64);
binData.remove(0, 64);
d = dataPiece.toULongLong(0, 2);
result += QByteArray::number(d);
}
_com->write(result);
_com->flush();
Where _com is a pointer to QtSerialPort, with all parameters set and opened without errors.

Qt QByteArray issue

I've tried the following:
qDebug() << QByteArray("\x00\x10\x00\x00").size();
and i get 0 instead of 4 witch i would espect.
What would be a good data type to hold this 4 bytes of data as i need to later write them to a socket so they must remain exactly like you see them above?
The constructor QByteArray(const char* str) uses qstrlen on the argument. Since your string starts with a 0x00 byte, qstrlen returns 0, thus the resulting QByteArray is 0 bytes long.
To avoid the qstrlen check, use the QByteArray(const char* str, int size) constructor:
qDebug() << QByteArray("\x00\x10\x00\x00", 4).size();
will print 4 as you expect.

QByteArray to integer

As you may have figured out from the title, I'm having problems converting a QByteArray to an integer.
QByteArray buffer = server->read(8192);
QByteArray q_size = buffer.mid(0, 2);
int size = q_size.toInt();
However, size is 0. The buffer doesn't receive any ASCII character and I believe the toInt() function won't work if it's not an ASCII character. The int size should be 37 (0x25), but - as I have said - it's 0.
The q_size is 0x2500 (or the other endianness order - 0x0025).
What's the problem here ? I'm pretty sure q_size holds the data I need.
Something like this should work, using a data stream to read from the buffer:
QDataStream ds(buffer);
short size; // Since the size you're trying to read appears to be 2 bytes
ds >> size;
// You can continue reading more data from the stream here
The toInt method parses a int if the QByteArray contains a string with digits. You want to interpret the raw bits as an integer. I don't think there is a method for that in QByteArray, so you'll have to construct the value yourself from the single bytes. Probably something like this will work:
int size = (static_cast<unsigned int>(q_size[0]) & 0xFF) << 8
+ (static_cast<unsigned int>(q_size[1]) & 0xFF);
(Or the other way around, depending on Endianness)
I haven't tried this myself to see if it works but it looks from the Qt docs like you want a QDataStream. This supports extracting all the basic C++ types and can be created wth a QByteArray as input.
bool ok;
q_size.toHex().toInt(&ok, 16);
works for me
I had great problems in converting serial data (QByteArray) to integer which was meant to be used as the value for a Progress Bar, but solved it in a very simple way:
QByteArray data = serial->readall();
QString data2 = tr(data); //converted the byte array to a string
ui->QProgressBar->setValue(data2.toUInt()); //converted the string to an unmarked integer..
This works for me:
QByteArray array2;
array2.reserve(4);
array2[0] = data[1];
array2[1] = data[2];
array2[2] = data[3];
array2[3] = data[4];
memcpy(&blockSize, array2, sizeof(int));
data is a qbytearray, from index = 1 to 4 are array integer.
Create a QDataStream that operates on your QByteArray. Documentation is here
Try toInt(bool *ok = Q_NULLPTR, int base = 10) const method of QByteArray Class.
QByteArray Documentatio: http://doc.qt.io/qt-5/QByteArray.html

Resources