QT实现IEEE754转换

  

由于需要和OMRON PLC进行FINS通信,所以需要进行格式转换。

 

①浮点转16进制字符串

QString MainWindow::ieee754_float_to_hex_str(QString str){

    const float value =  str.toFloat();
    const quint32 *i = reinterpret_cast<const quint32 *>(&value);

    QByteArray ba;
    ba.append(char(*i >> 24));
    ba.append(char(*i >> 16));
    ba.append(char(*i >>  8));
    ba.append(char(*i >>  0));
    return ba.toHex().toUpper();

}

 

②16进制字符串转浮点

float MainWindow::ieee754_hex_str_to_float(QString str){

    const QByteArray ba = QByteArray::fromHex(str.toLatin1());

    if (ba.size() != 4){
        return 0;
    }

    quint32 word = quint32((quint8(ba.at(0)) << 24) |
                           (quint8(ba.at(1)) << 16) |
                           (quint8(ba.at(2)) <<  8) |
                           (quint8(ba.at(3)) <<  0));

    const float *f = reinterpret_cast<const float *>(&word);
    return *f;

}

 

posted @ 2021-06-19 00:54  hiwjy  阅读(649)  评论(0编辑  收藏  举报