Reputation: 948
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.
Upvotes: 12
Views: 20695
Reputation: 49
From unsigned char* to QString:
unsigned char *str_uchar;
QString str = QString::fromUtf8((char*)str_uchar);
From QString to unsigned char*:
QString str;
unsigned char *str_uchar = (unsigned char*)(str.toUtf8().data());
Upvotes: -1
Reputation: 1
int lengthOfString = strlen( reinterpret_cast(str) );//bug,when try to get the length like "00889966"
QString getStringFromUnsignedChar( unsigned char *str, const int len ){
QString result = "";
int lengthOfString = len );
// 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;
}
Upvotes: 0
Reputation: 3734
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;
}
Upvotes: 7
Reputation: 106
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;
}
Upvotes: 7