1. 四舍五入保留小数几位
QString str="12.3456789"; double d1=str.toDouble(); qDebug()<<"d1"<<d1;//12.3457 QString str1=QString::number(d1,'f',3);//3 保留几位小数 qDebug()<<"str1"<<str1;//12.346
2.
QByteArray macAddress = QByteArray::fromHex("123456abcdef"); qDebug()<<"macAddress:"<<macAddress.toHex(':');//12:34:56:ab:cd:ef
QByteArray ba; ba.resize(3); ba[0]=0x7E; ba[1]=0x51; ba[2]=0x7E; qDebug()<<ba.toHex(' ');//7e 51 7e"
4.QString -> char*
#include<QTextCodec>
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); QString str="中国人民"; char* ch; // QByteArray ba = str.toLatin1(); QByteArray ba = str.toLocal8Bit(); ch=ba.data(); qDebug()<<ch;
QString qstr="abcdef"; std::string str_data = qstr.toStdString(); int size=str_data.size (); const char * char_data=str_data.c_str ();
5. char*-> QString
QString str; char *msg; str = QString::fromLocal8Bit(msg);
char* data=new char[3]; data[0]=0x01; data[1]=0x02; data[2]=0x03; QString qstr = QString(QLatin1String(data));//abc
6.十进制转化二进制,指定位数,不够补零
int a=10; QString str = QString("%1").arg(a,8,2,QLatin1Char('0')); qDebug()<<"---->"<<str; //----> "00001010"
7.无符号数转换有符合数,modbus读取数据16位时候,有什么需要是负数。原则是:最高位如果是1就是负数,然后取反,加1,添加负号,就是所要的负值。
int AgvProtocol::uintToInt(uint16_t ut) { QString binaryStr=QString("%1").arg(ut,16,2,QLatin1Char('0')); qDebug()<<"modbus readbinaryStr:"<<binaryStr; if(binaryStr[0]=='1') { int len=binaryStr.length(); int nDec=0; for(int i=0;i<len;i++){ if(binaryStr[i]=='0'){ int k=1; for(int j=0;j<len-i-1;j++) { k=k*2; } nDec+=k; } } return -(nDec+1); } else { return ut; } }
8.char数组 16进制显示
QString Common::binToHexString(const uint8_t *data,size_t size) { std::ostringstream strHex; strHex << std::hex << std::setfill('0'); for (size_t i = 0; i < size; ++i) { strHex << std::setw(2)<<std::setiosflags(std::ios::uppercase)<<static_cast<unsigned int>(data[i])<<' '; } return QString::fromStdString(strHex.str()); }
char* data=new char[3]; data[0]=0x61; data[1]=0x62; data[2]=0x63; QString qstr=binToHexString((uint8_t*)data,3);//61 62 63