Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert unsigned char * to QString

Tags:

c

qt

I know this is a very basic question but sometimes it happens that you loose your basic concept :) Tried Goggling but not enough support on that too.

I am using predefined library from one of our device owner. They have a declaration as :

unsigned char FamilySerialNum[0][8]

This variable gets the serial number of the device in hexadecimal. Now i am using this library in Qt to display the serial number in QLineEdit. For that I need to convert it to QString.

Tried using QString::UTF8, strcpy(), sprintf() etc. but getting garbage data.

So can anyone suggest me some way to get it done.

like image 323
skg Avatar asked Sep 14 '12 02:09

skg


2 Answers

Hello Try the function below...

QString getStringFromUnsignedChar(unsigned char *str)
{

    QString s;
    QString result = "";
    int rev = strlen(str); 

    // Print String in Reverse order....
    for ( int i = 0; i<rev; i++)
        {
           s = QString("%1").arg(str[i],0,16);

           if(s == "0"){
              s="00";
             }
         result.append(s);

         }
   return result;
}
like image 74
user1550798 Avatar answered Oct 11 '22 22:10

user1550798


User1550798's answer is very close but doesn't quite work (some outputs it produces are corrupted), since it only converts the value "0" to a zero-padded 2 character output (ie: "00"). Instead any single-digit hex values should be be padded with a zero (ie: "3" --> "03").

Try the following instead:

QString getStringFromUnsignedChar( unsigned char *str ){
    QString result = "";
    int lengthOfString = strlen( reinterpret_cast<const char*>(str) );

    // print string in reverse order
    QString s;
    for( int i = 0; i < lengthOfString; i++ ){
        s = QString( "%1" ).arg( str[i], 0, 16 );

        // account for single-digit hex values (always must serialize as two digits)
        if( s.length() == 1 )
            result.append( "0" );

        result.append( s );
    }

    return result;
}
like image 21
Marchy Avatar answered Oct 11 '22 20:10

Marchy