类型转化

从串口读取到的QByteArray数据,一般需要进行提取和解析,此时就需要QByteArray转换为各类型数据。1 转为HEX,2 转为不同进制数值并显示   3 转为整型、浮点型等数值类型;  4 转为字符串类型;

十六进制字符转化成int

int hexCharToInt(char c)

{
    if (c >= '0' && c <= '9') return (c - '0');
    if (c >= 'A' && c <= 'F') return (c - 'A' + 10);
    if (c >= 'a' && c <= 'f') return (c - 'a' + 10);
    return 0;
}

 

int 转化为QByteArray

QByteArray uintToByte_1(uint number)
{
    QByteArray abyte;
    abyte.resize(4);
    abyte[3] = (uchar)  (0x000000ff & number);
    abyte[2] = (uchar) ((0x0000ff00 & number) >> 8);
    abyte[1] = (uchar) ((0x00ff0000 & number) >> 16);
    abyte[0] = (uchar) ((0xff000000 & number) >> 24);
    return abyte;
}

 

hexstring    转化为char* 

char *HMPCADefine::hexstringToBytes(string s)
{
    int sz = s.length();  //
    char *ret = new char[sz/2];
    for (int i=0 ; i <sz ; i+=2) {
        //                         获取高4位                   获取低4位
        ret[i/2] = (char) ((hexCharToInt(s.at(i)) << 4)| hexCharToInt(s.at(i+1)));
    }
    return ret;
}

 

posted @ 2019-08-10 14:02  countryboy666  阅读(171)  评论(0编辑  收藏  举报