0

I am making my Qt program with C++. I am reading a value from a card Reader but its libraries gives me the value with an unsigned char*. And I needit in Qstring to put it in a QTextEdit.

I have tried:

char* aux(reinterpret_cast<char*>(data->track2));
QString myString = QString::fromUtf8(aux);

I can read my unsigned char like this:

for(int x = 0; x < len; x++){
         printf("%02X", buf[x]);
     }

But I get very strange values. Anyone can help me? Or how can I push that unsigned char* (buf) in a string?

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
Roger Coll
  • 117
  • 1
  • 3
  • 12
  • 3
    `QString myString = QString::fromUtf8(aux);` should be fine. But are you sure that the data that you read isn't binary (although it seems so)? Maybe the text you want to display is only part of the data that you read (which might contain some extra *control chars* - let's name them so - that shouldn't be displayed since they could be part of a lower level protocol). – CristiFati Jan 14 '18 at 22:58

2 Answers2

3

UTF8 C-String

Qt stores it's strings as UTF-16, and previously (in Qt3) as UCS2. This means that it is not similar to a C-string, since the string is based on 16-bit (multi-byte) characters.

To convert data to a QString from a UTF8-encoded C-string or array and length, you should use.

char data[] = "My string";
QString qstr1 = QString::fromUtf8(data);
QString qstr2 = QString::fromUtf8(data, strlen(data));

To convert back to a C-string, you should use:

QByteArray bytes = qstr1.toUtf8();
const char* data = bytes.constData(); 

Other Encodings

If your data is not UTF-8, you will have to use a different helper function. Qt provides fromLatin1 and toLatin1 for simple European code pages, and also the local narrow code page with fromLocal8Bit and toLocal8Bit.

Summary

Your char* is not the same encoding as a Q-String. Don't try to directly add individual characters (unless they are a single code point) to a Q-string. Use the helper functions to ensure you are combining data with the same encoding.

Alex Huszagh
  • 13,272
  • 3
  • 39
  • 67
0
unsigned char* ch;  
std::string test= (char*)ch;  
QString sstr = QString::fromStdString(test); 

I use this and it work.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
lijinghan
  • 9
  • 1