0

I am trying to convert char* to QString. It should be a trivial task but the problem is, I am having the following input:

item    char [512] "N"  char [512]
    [0] 78 'N'  char
    [1] 0 '\0'  char
    [2] 73 'I'  char
    [3] 0 '\0'  char
    [4] 70 'F'  char
    [5] 0 '\0'  char
    [6] 84 'T'  char
    [7] 0 '\0'  char
    [8] 89 'Y'  char
    [9] 0 '\0'  char
    [10]    0 '\0'  char

Notice the null character after each character '\0'. Simply trying to convert it just yields the string "N" where as it should result into string "NIFTY".

I am not sure if it is unicode or Ansi string (in fact I don't know much about it). Can anyone please sort out what is going wrong here or what am I missing?

Angie Quijano
  • 4,167
  • 3
  • 25
  • 30
Murtuza Kabul
  • 6,438
  • 6
  • 27
  • 34
  • Seems to be unicode. Try `wchar_t`. – Synxis Oct 31 '12 at 08:11
  • 1
    It does seem to be Unicode (UTF-16 to be precise). But that would require another trailing '\0' byte. If that's missing you have a problem. – john Oct 31 '12 at 08:14
  • Casting to `QChar*` might well work, it would be better to get the data into the right type in the first place though. I think you need to go back a step and show us where you got the data in the first place. Apart from anything else you would learn a bit more about ANSI and Unicode. – john Oct 31 '12 at 08:16
  • Scratch that, QChar* didn't work for me. QString::fromUtf16((ushort*)buffer) however did, but you need one more 0 char at the buffer end to form a valid zero termination – Ancurio Oct 31 '12 at 08:23

2 Answers2

1

This worked for me:

    char * chr = "N\0I\0F\0T\0Y\0\0";
    QString str = QString::fromUtf16((ushort*)(chr));
    qDebug() << str;
opc0de
  • 11,557
  • 14
  • 94
  • 187
-1
 char name[13] = "StudyTonight";


 int namelen = strlen(name);

 QString  result = QString::fromUtf8((const char *)name,namelen);

 qDebug() << result
Milind Morey
  • 2,100
  • 19
  • 15
  • 2
    You should care to explain why you think it solves the askers problem (but I'm rather sure it won't work this way, so you should re-check your answer and your assumptions). – Murphy Aug 19 '20 at 11:57