Convert QString into unsigned char array

samoncode picture samoncode · Feb 18, 2014 · Viewed 25.3k times · Source

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?

Answer

4pie0 picture 4pie0 · Feb 18, 2014

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'.