Convert QString hexadecimal to ASCII value - c++

My goal is to convert an hexadecimal value which is contained in a QString to its ASCII value.
I have :
QString hexaValue = receiveText.left(14); // receive texte is another QString
My problem here, is that I have my hexadecimal value in a Qstring and not in a QByteArray, so all of the solutions that I found are not working, I try to call .data() or fromHex() , but this ain't working here, because I'm forced to used a QString and not a QByteArray
Should I convert my QString to a QByteArray, is there a simple solution ?

You can just use QString::toLatin1to convert hex string to QByteArray and to convert it back to QString use either QString::fromLocal8Bit for local encoding or QString::fromUtf8 if your hex encoded string are in UTF8.
QString hexaValue = receiveText.left(14); // received text is another QString
QString textValue = QString::fromLocal8Bit(QByteArray::fromHex(hexaValue.toLatin1()));

Related

How to convert QString with special characters into a byte stream to send it via Linux pipe

I have a QString containing a special character (µ) encoded in UTF-8:
QString data = "197,45 \xc2\xb5m";
I need to send that string via a Linux pipe to another program. I tried to convert the string into something like this:
char msg[15];
for(int i = 0; i < data.length(); i++) {
msg[i] = data.toUtf8()[i];
}
msg[data.length()] = '\0';
I send msg to the pipe, but I only receive "197,45 µ", not "197,45 µm". I try to read the data on the read end with:
char data[15];
read(fd, data, nbytes);
I don't know much about character/string conversion, so I would be glad if you could explain how I should approach this problem. Thank you.
What you are doing seems to be mainly "serializing the data" into a binary pipe, so an option that could make sense is to use a QDataStream which is designed for that purpose.
Something like:
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::WriteOnly);
QString data = "197,45 \xc2\xb5m";
stream << data;
sendToPipe(buffer.constData(), buffer.size());
And the similar on the other side, using operator>> to read the data from the stream.
QByteArray buffer(dataPtr, size);
QDataStream stream(buffer);
QString data;
stream >> data;
It is conceptually wrong to store UTF-8 encoded bytes in a QString. Use QByteArray for that, OR use QString::fromUtf8() to convert your UTF-8 string literals to a proper QString. To go back, use the qUtf8Printable macro or QString::toUtf8 to get a QByteArray.

Converting a QString with a binary into a QString with a hex

I am wondering what the most efficient way would be to convert a binary that is saved as a QString into the corresponding Hex and save it in the same QString
QString value = "10111100"
into
value = "bc"
It's simple. First convert your binary string to an integer:
QString value = "10111100";
bool fOK;
int iValue = value.toInt(&fOk, 2); //2 is the base
Then convert the integer to hex string:
value = QString::number(iValue, 16); //The new base is 16

Qt C++ QString to QByteArray Conversion

I have created an encrypt/decrypt program, when encrypting I store the encrypted QByteArray in a text file.
When trying to decrypt I retrieved it and then put it into the decryption method, the problem is that I need a way to convert it to QByteArray without changing the format, otherwise it will not decrypt properly. What I mean is if the file gave me an encrypted value of 1234 and I converted that to QByteArray by going 1234.toLatin1() it changes the value and the decryption does not work. Any suggestions?
My Code:
QFile file(filename);
QString encrypted;
QString content;
if (file.open(QIODevice::ReadOnly)) {
QTextStream stream( &file );
content = stream.readAll();
}
encrypted = content.replace("\n", "");
qDebug() << encrypted; // Returns correct encrypted value
QByteArray a;
a += encrypted;
qDebug() << "2 " + a; // Returns different value than previous qDebug()
QByteArray decrypted = crypto.Decrypt(a, key);
return decrypted;
I guess you should use:
QString::fromUtf8(const QByteArray &str)
Or:
QString::QString(const QByteArray &ba)
to convert QByteArray to QString, then write it into file by QTextStream.
After that, read file by QTextStream, use:
QString::toUtf8()
to convert QString to QByteArray.
QString::QString(const QByteArray &ba)
Constructs a string initialized with the byte array ba. The given byte array is converted to Unicode using fromUtf8().
P.S:
Maybe use QFile::write and QFile::read is a better way.
try using toUtf8() .. it works fine with me
If I understand correctly, the text from the file is store in the QString content. I think you could create a new QByteArray. Because the constructor of a QByteArray does not allow a QString as input, I will probably have to append the QString to the empty QByteArray.
//After if:
QByteArray tempContent();
tempContent.append(content);
QByteArray decrypted = crypto.Decrypt(tempContent, key);
I do not have much experience in the Qt library, but I hope this helps.
Or simply go with b64 = data.toUtf8().toBase64();
First convert it to QByteArray with the toUtf8() and then immediately convert it to toBase64()
There's a simple way :
QByteArray ba;
QString qs = "String";
ba += qs;
More hard way:
QByteArray ba;
QDataStream in(&ba, QIODevice::WriteOnly);
in << QString("String");
Extreme way, for people who want to use QBuffer:
#include <QDebug>
#include <QBuffer>
#include <QDataStream>
#include <QIODevice>
#include <QByteArray>
#include <QString>
#include <qcoreapplication.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QByteArray byteArray;
QBuffer buffer(&byteArray);
buffer.open(QIODevice::ReadWrite);
QDataStream in( &buffer );
in << QString("String");
buffer.close();
for (int i = 0; i < byteArray.length(); ++i) {
printf("%c - %x\n", byteArray.at(i), byteArray.at(i));
}
printf("\n");
return a.exec();
}
Who run last code can ask me where does the null byte come from?
QDataStream serializes the QString as a little-endian. 4 bytes are read to create the 32-bit length value, followed by the string itself in UTF-16. This string length in UTF-16 is 12 bytes, so the first three bytes in QByteArray will be zero.
There is often a problem with reading the QByteArray in qDebug () The recording is fine.
Don't forget to remove QT_NO_CAST_FROM_BYTEARRAY in your .pro file, if it has

Displays unwanted character while converting from QDataStream to QChar

I have a code as below
QByteArray bla("abcde");
QDataStream ds(bla.right(bla.size()-1));
QChar c;
ds>>c;
qDebug()<<c; // It prints '?' instead of 'b'
It prints out b if I change the code as
qint8 c;
ds>>c;
qDebug()<<QChar(c); // It now prints 'b'.
It's ok for a single character suppose, I have a lot of characters then I need to make a loop and cast every single of them . Please suggest a good approach.
ds>>c; equals ds>>c.unicode();, which has type ushort &. While QByteArray contains chars.
The correct way to converting QBytaArray to a sequence of QChar would be:
QByteArray bla("abcde");
QTextCodec *codec = QTextCodec::codecForLocale();
const QString string = codec->toUnicode(bla);
foreach (const QChar &c, string) {
qDebug() << c;
}

Sending a big buffer through uart in Qt5

I'm a beginner in Qt. Now I want to use Qt5 to send a 9-byte command through uart.
Here is my command:
FFFFFF5550464DAA0E
I want to transfer my command to a Qstring object. When I write my code like this, it tells me the const is too big.
QString str=0xFFFFFF5550464DAA0E;
So I choose an array like this, but it still doesn't work.
char cmd[9]={0xFF,0xFF,0xFF,0x55,0x50,0x46,0x4D,0xAA,0x0E};
for(int i=0;i<9;i++)
{
QString str=cmd[i];
QByteArray outData=str.toLatin1();
int size=outData.size();
outData=myHelper::HexStrToByteArray(str);
size=outData.size();
myCom->write(outData);
}
I also try this which failes again
char cmd[9]={0xFF,0xFF,0xFF,0x55,0x50,0x46,0x4D,0xAA,0x0E};
QString str=cmd;
QByteArray outData=str.toLatin1();
int size=outData.size();
outData=myHelper::HexStrToByteArray(str);
size=outData.size();
myCom->write(outData);
So could anyone tell me how to do this ?
This line of code:
QString str=0xFFFFFF5550464DAA0E;
0xFFFFFF5550464DAA0E is not a string. You're trying to assign a very big constant (9 bytes) number to a string. Note that 0xFF is not a string but a character with ASCII code 0xFF. With your second attempt you're on the right way:
char cmd[9]={0xFF,0xFF,0xFF,0x55,0x50,0x46,0x4D,0xAA,0x0E};
Now you have two options; it depends on what you have to send, 9 bytes or a longer string with that commands represented as a hex string and encoded as ASCII. First case is easier, drop all your code:
QByteArray outData = QByteArray(cmd, sizeof(cmd));
myCom->write(outData);
With this code you won't send a string to your device but 9 bytes (0xFF...0x0E). If you have to send a string then you can do what paxdiablo suggested:
QByteArray outData = QByteArray("\xFF\xFF\xFF\x55\x50\x46\x4D\xAA\x0E", 9);
myCom->write(outData);
Or:
QByteArray outData = QString("0xFF0xFF0xFF0x550x500x460x4D0xAA0x0E")
.toLatin1();
myCom->write(outData);
Or in alternative you can do this:
char cmd[9]={0xFF,0xFF,0xFF,0x55,0x50,0x46,0x4D,0xAA,0x0E};
QByteArray outData = QByteArray(cmd, sizeof(cmd)).toHex();
myCom->write(outData);
Which one is right for you? Well you should clarify your context...
You don't need to mess about with strings and conversions. You can just make the QByteArray directly from the data itself, with a simple one-liner:
QbyteArray data("\xFF\xFF\xFF\x55\x50\x46\x4D\xAA\x0E", 9);
Following that, the statement:
myCom->write(data);
will then output the nine bytes as specified in the string.