Peter
Peter

Reputation: 69

Convert unsigned char* to QString and vice versa

I am trying to convert const unsigned char* to QString and vice versa. I have managed to convert it in one direction, but not from QString to const unsigned char*. I've seen a lot of similiar questions, but none of the solutions worked for me.

Here is my sample code :

void f(const unsigned char* addr)
{
 QString data = QString::fromLatin1((const char*)addr, len);  //should work correctly
 
 unsigned char* cc = new unsigned char[data.size()];
 memcpy(cc, data.toStdString().c_str(), data.size());   //isn't working
}

My check for a solution : len = 8 in this example, therefore :

data contains :

data content

unsigned char buff[8];
for (int i = 0; i < 8; i++)
    buff[i] = cc[i];
//buff now contains [194,128,6,0,1,0,0,18]

unsigned char bb[8];
memcpy(bb, addr, 8);
//bb contains [128,6,0,1,0,0,18,0]

Is there any other way ? Thank you for any input.

Upvotes: 0

Views: 1045

Answers (1)

john
john

Reputation: 88007

So here's a clue as to what is really going on. In your original string you have the byte sequence 194 128. That's a possible the encoding for the Euro symbol in UTF-8. In your output that has been replaced by the single byte 128, which is the encoding for the Euro symbol in the Windows-1252 code page.

So somewhere in your code there is a change of encoding happening, which explains why you see the difference in input and output. Almost certainly that change is happening because of one or other of the QString functions you are using.

Solving this problem is not really possible without know more about what you are actually doing. If your byte arrays do not represent text then it's a mistake to put them into a QString since these are used for Unicode text not arbitrary byte arrays.

Upvotes: 1

Related Questions