c语言实现浮点数和16进制数的转化

⌚Time: 2022-12-10 20:44:28

👨‍💻Author: Jack Ge

PLC通常将浮点数据类型直接以16进制数据的形式发送给上位机

上位机程序要进行数据的读取和发送,就需要进行浮点数据和16进制数据的转换

16进制转浮点


//16进制转浮点

float hex_2_float(unsigned char a,unsigned char b,unsigned char c,unsigned char d){

    unsigned char pMem[4];

    pMem[0] = d;

    pMem[1] = c;

    pMem[2] = b;

    pMem[3] = a;

    float *p = (float*)pMem;

    return *p;

}

浮点转16进制


//浮点转16进制

unsigned long float_2_hex(float num){

    union {

        long int number;

        float fnumber;

    }A;

    A.fnumber = num;

    return A.number;

}

测试程序


// Example program

#include <stdio.h>

#include <string.h>



//16进制转浮点

float hex_2_float(unsigned char a,unsigned char b,unsigned char c,unsigned char d){

    unsigned char pMem[4];

    pMem[0] = d;

    pMem[1] = c;

    pMem[2] = b;

    pMem[3] = a;

    float *p = (float*)pMem;

    return *p;

}

//浮点转16进制

unsigned long float_2_hex(float num){

    union {

        unsigned long number;

        float fnumber;

    }A;

    A.fnumber = num;

    return A.number;

}

int main()

{

  

  printf("1.1f to hex: %08x\n",float_2_hex(1.10f));

  printf("0x3f8ccccd to float: %.2f\n",hex_2_float(0x3f,0x8c,0xcc,0xcd));

  return 0;

}

结果

对于16进制数据的收发,一定要格式化数据长度并且用0占空位。比如对于4字节数据0x3f,发送为00 00 00 3f而不是3f。