QT——QString转QByteArray16进制并自动补0

void MainWindow :: String2Hex ( QString str , QByteArray & senddata )

{


int hexdata,lowhexdata;


int hexdatalen = 0;


int len = str.length();


senddata.resize(len/2);


char lstr,hstr;


for(int i=0; i

{


//char lstr,


hstr=str[i].toLatin1();


if(hstr == ' ')


{


i++;


continue;


}


i++;


if(i >= len)


break;


lstr = str[i].toLatin1();


hexdata = https://www.it610.com/article/ConvertHexChar(hstr);


lowhexdata = https://www.it610.com/article/ConvertHexChar(lstr);


if((hexdata =https://www.it610.com/article/= 16) || (lowhexdata == 16))


break;


else


hexdata = https://www.it610.com/article/hexdata*16+lowhexdata;


i++;


senddata[hexdatalen] = (char)hexdata;


hexdatalen++;


}


senddata.resize(hexdatalen);


} char MainWindow::ConvertHexChar(char ch)

{

if((ch >= '0') && (ch <= '9'))

return ch-0x30;

else if((ch >= 'A') && (ch <= 'F'))

return ch-'A'+10;

else if((ch >= 'a') && (ch <= 'f'))

return ch-'a'+10;

else return (-1);

}

int main()
{

QString dbm ;
QByteArray db_m;
char db_buff[10]={0};

dbm = ui -> lineEdit_dB -> text ();
unsigned int db = dbm . toInt ();
sprintf ( db_buff , "%x" , db );
if ( strlen ( db_buff )% 2 )
{

qDebug("奇数");

for(i=0; i
{

db_buff[strlen(db_buff)-i+1] = db_buff[strlen(db_buff)-i];

}

db_buff[0]='0';

dbm=QString::fromLocal8Bit(db_buff,strlen(db_buff));

qDebug("db_buffm%s",db_buff);

memset(db_buff,0,strlen(db_buff));

}

else

{

dbm=QString::fromLocal8Bit(db_buff,strlen(db_buff));

}

String2Hex(dbm,db_m); serial->write(db_m);

}

    推荐阅读