How to convert ASCII Hex string to Byte array?
-
Hi,
I try to convert a string, containing hex chars only, to a byte array. I could do it in C but in Qt I did not find any solution :) . Yes it is easy and trivial but really I need help.Lets say I have a string like "E00200BA9EFC00AC", how can I convert it to an array like this:
bytearray[0]=0xE0
bytearray[1]=0x02
bytearray[2]=0x00
bytearray[3]=0xBA
....
bytearray[7]=0xAC -
Hi,
Do you mean something like QByteArray::fromHex ?
-
Do you mean a std::string or "MyHexString" ?
-
Then why not do as the example in the doc suggests:
QByteArray myHexArray = QByteArray::fromHex("E00200BA9EFC00AC");
?
-
@SGaist
Becausue fromHex accepts QByteArray as parameter, I have QString. Later I will get this string from UI element, QLineEdit
(ui->cmdToWrite->text(), this is QString)QString MyHexString = "E00200BA9EFC00AC"; QByteArray cmd = QByteArray::fromHex(MyHexString);
Error message:
D:\Qt\Projects\Widget\mainwindow.cpp:40: error: no matching function for call to 'QByteArray::fromHex(QString&)'
QByteArray cmd = QByteArray::fromHex(MyHexString);
^ -
@kahlenberg Take a look to this member function:
QByteArray QByteArray::fromHex(const QByteArray & hexEncoded)
Joaquim Duran
-
Again, why create a QString ? Just use QByteArray directly or if you really really want a QString, use e.g. toLatin1
-
@kahlenberg : could you post the code? I am in the same situation.
-
QString MyHexString = "E00200BA9EFC00AC";
QByteArray cmd = QByteArray::fromHex(MyHexString);You simply have to use
QString::toLatin1()
:QString MyHexString = "E00200BA9EFC00AC"; QByteArray cmd = QByteArray::fromHex(MyHexString.toLatin1());
-
monitorCommand = "020400000006703B"; QByteArray data_to_transmit = QByteArray::fromHex(monitorCommand.toUtf8());
qDebug() << monitorCommand << data_to_transmit;
it gives "020400000006703B for monitorcommond
for data_to_transmit "\x02\x04\x00\f\x00\x06\xB0""8"
but its not correctly converted to hex -
@mganesh This works fine for me. Your output can not match on what you've written. Please post all your test code
int main(int argc, char **argv) { QCoreApplication app(argc, argv); QString monitorCommand = "020400000006703B"; QByteArray data_to_transmit = QByteArray::fromHex(monitorCommand.toUtf8()); qDebug() << monitorCommand << data_to_transmit; return 0; }
-->
"020400000006703B" "\x02\x04\x00\x00\x00\x06p;"