qt 几个有点价值的个人创建的程序,字符串转ascii,字符串转hex,hex转字符,时间bcd互转字符串,小数转字符串(直接使用qt的转有bug)(虽然网上有很多c的,但是qt写出来的,更加简洁)

 

 

//

//时间转换2021-01-07 12:12:12  =>0x21 0x01 0x07 0x12 0x12 0x12
void Hun::strTimeToBCD(char *tem, QString time)
{
    bool ok;
    tem[0] = time.mid(2,2).toUInt(&ok,16);
    tem[1] = time.mid(5,2).toUInt(&ok,16);
    tem[2] = time.mid(8,2).toUInt(&ok,16);
    if(time.length()>10){
        tem[3] = time.mid(11,2).toUInt(&ok,16);
        tem[4] = time.mid(14,2).toUInt(&ok,16);
        tem[5] = time.mid(17,2).toUInt(&ok,16);
    }
}

QString Hun::BCDToStrTime(char *tem, int len)
{
    bool ok;QString temstr="";
    QString time = QByteArray(tem,len).toHex();//21 02 24 10 12 13
    if     (len==1)temstr = "20"+time;
    else if(len==2)temstr = "20"+time.mid(0,2)+"-"+time.mid(2,2);
    else if(len==3)temstr = "20"+time.mid(0,2)+"-"+time.mid(2,2)+"-"+time.mid(4,2);
    else if(len==4)temstr = "20"+time.mid(0,2)+"-"+time.mid(2,2)+"-"+time.mid(4,2)+" "+time.mid(6,2)+":00:00";
    else if(len==5)temstr = "20"+time.mid(0,2)+"-"+time.mid(2,2)+"-"+time.mid(4,2)+" "+time.mid(6,2)+":"+time.mid(8,2)+":00";
    else           temstr = "20"+time.mid(0,2)+"-"+time.mid(2,2)+"-"+time.mid(4,2)+" "+time.mid(6,2)+":"+time.mid(8,2)+":"+time.mid(10,2);

    return temstr;
}

//u32 数据缩小100倍之后,转字符串小数显示
QString Hun::formatData(u32 *tem, int len)
{
    QString t = "\n";
    for(int i=0;i<len;i++){
        t+=QString("  %1.%2").arg(tem[i]/100).arg(tem[i]%100);
        if((i+1)%12==0)t+="\n";if((i+1)%24==0)t+="\n";
    }
    return t;
}


//hex转字符串 QByteArray有个toHex()函数可以直接转为hex字符串显示
//字符串转hex 在转换时候直接使用字符串的toUInt(&ok,16)函数可以直接显示,其中&ok可以直接使用nullptr代替
//char转uchar不会丧失数据,可以大胆转, 案例如下
QString meterNumber = "0000000100000001";
char bcd[8];bool ok;
for(int i=0;i<8;i++){bcd[i] = meterNumber.mid(2*i,2).toUInt(&ok,16);}
QString te1 = QByteArray((char*)bcd,8).toHex();//te1=>0000000100000001

 

 

 

//

posted @ 2021-03-16 14:22  小城熊儿  阅读(511)  评论(0编辑  收藏  举报