PDA

View Full Version : QString convert to QByteArray



schunyeh
23rd January 2015, 00:34
Hi,
Are there any way to convert a QString as following data to QByteArray?
I try to code as following, but it cannot work.


QString test_raw1 = "0x01";
QString test_raw2 = "0x8a";
QByteArray tmp_byte;
tmp_byte.resize(2);
tmp_byte[0].insert(0,test_raw1);
tmp_byte[1].insert(1,test_raw1);

I would like to have a result as following.


QByteArray tmp_byte;
tmp_byte.resize(2);
tmp_byte[0]=0x01;
tmp_byte[1]=0x8a;

Could anyone please help me.
Thank you very very much.

jefftee
23rd January 2015, 02:05
Are those hex bytes you're trying to add to a QString, only to then put into a QByteArray supposed to represent a particular text encoding? QString internally stores text encoded as UTF-16.

Why not just append the hex bytes directly to a QByteArray as follows:


QByteArray tmp_array;
tmp_array.append(0x01);
tmp_array.append(0x8a);


Not sure I understand why you're trying to use QString at all here. If you do really have a QString that you want to put into a QByteArray, look at the various QString::to* methods, like QString::toUtf8() for example.

anda_skoa
23rd January 2015, 08:49
In case you want the numerical values in the string, see QString::toInt(), using a base of 16

Cheers,
_

Lesiok
23rd January 2015, 09:32
Read about QByteArray::fromHex

schunyeh
28th January 2015, 00:20
Thank jthomps,anda_skoa,Lesiok for the reply.
The case is that I would like to input a text file that has a decimal number, and then got the numer to change them to the hexadecimal format ( 0xff), & write them to a special binary file format ( 008a 001a .... ..... ).
After trying to convert, I have found the following API can do it.


QString test_number; // "0x8a"
QByteArray test_hex;
test_hex = QByteArray::fromHex( test_number.toLocal8Bit().constData() );
qDebug()<<test_hex.at(1); // 0x8a

Thank you for the help.