Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert QString into unsigned char array

I have a very basic question here. I tried googling for a while, because there are a lot of similar questions but none of the solutions worked for me.

here is a code snippet that shows the problem:

QString test = "hello";
unsigned char* test1 = (unsigned char*) test.data();
unsigned char test2[10];
memcpy(test2,test1,test.size());
std::cout<<test2;

I try to fit the QString into the unsigned char array but the output I get is always just 'h'.

Can anyone tell me what is going wrong here?

like image 433
samoncode Avatar asked Jan 12 '23 04:01

samoncode


2 Answers

Problem is in that QString.data() returns a QChar* but you want const char*

QString test = "hello";
unsigned char test2[10];
memcpy( test2, test.toStdString().c_str() ,test.size());
test2[5] = 0;
qDebug() << (char*)test2;
             ^^^
            this is necessary becuase otherwise
            just address is printed, i.e. @0x7fff8d2d0b20

The assignment

unsigned char* test1 = (unsigned char*) test.data();

and trying to copy

unsigned char test2[10];
memcpy(test2,test1,test.size());

is wrong, because QChar is 16 bit entity and as such trying to copy it will terminate because of 0 byte just after 'h'.

like image 115
4pie0 Avatar answered Jan 14 '23 16:01

4pie0


In the second line you're trying to cast QChar* to (unsigned char*) which is completely wrong.

Try this:

QString test = "hello";
QByteArray ba = test.toLocal8Bit();
unsigned char *res = (unsigned char *)strdup(ba.constData());
std::cout << res << std::endl;
like image 36
hank Avatar answered Jan 14 '23 16:01

hank