C语言:单精度(float)和双精度(double)浮点数 与 十六进制(HEX) 之间转换
作者:互联网
1. 单精度(float) 转 十六进制(HEX)
(1)指针法
具体代码如下:
void Float_HEX (float fdata, unsigned char *hdata) { unsigned char* tdata = (unsigned char*)(&fdata); hdata[0] = tdata[0]; hdata[1] = tdata[1]; hdata[2] = tdata[2]; hdata[3] = tdata[3]; }
测试用例如下:
int main(int argc, char *argv[]) { unsigned char data[4] = {0,0,0,0}; float fdata = 12.66; Float_HEX(fdata,data); for(int i=0;i<4;i++) printf("0x%X\n",data[i]); return 0; }
(2)共用体法
具体代码如下:
union { float fdata; unsigned char data[4]; }temp;
试用例如下:
int main(int argc, char *argv[]) { temp.fdata = 12.66; for(int i=0;i<4;i++) printf("0x%X\n",temp.data[i]); return 0; }
由于我的电脑系统是小端模式,所以低字节在前。
运行结果如下:
(3)memcpy()函数法
具体代码如下:
void Float_HEX (float fdata, unsigned char *hdata) { memcpy(hdata,&fdata,sizeof(fdata)); }
测试用例如下:
int main(int argc, char *argv[]) { unsigned char data[4] = {0,0,0,0}; float fdata = 12.66; Float_HEX(fdata,data); for(int i=0;i<4;i++) printf("0x%X\n",data[i]); return 0; }
2. 双精度(double)转 十六进制(HEX)
(1)指针法
具体代码如下:
void Double_HEX (double Ddata, unsigned char *hdata) { unsigned char* tdata = (unsigned char*)(&Ddata); hdata[0] = tdata[0]; hdata[1] = tdata[1]; hdata[2] = tdata[2]; hdata[3] = tdata[3]; hdata[4] = tdata[4]; hdata[5] = tdata[5]; hdata[6] = tdata[6]; hdata[7] = tdata[7]; }
测试用例如下:
int main(int argc, char *argv[]) { unsigned char data[8] = {0,0,0,0,0,0,0,0}; double Ddata = 12.66; Double_HEX(Ddata,data); for(int i=0;i<8;i++) printf("0x%X\n",data[i]); return 0; }
(2)共用体法
具体代码如下:
union { double Ddata; unsigned char data[8]; }temp;
测试用例如下:
int main(int argc, char *argv[]) { temp.Ddata = 12.66; for(int i=0;i<8;i++) printf("0x%X\n",temp.data[i]); return 0; }
(3)memcpy()函数法
具体代码如下:
void Double_HEX (double Ddata, unsigned char *hdata) { memcpy(hdata,&Ddata,sizeof(Ddata)); }
测试用例如下:
int main(int argc, char *argv[]) { unsigned char data[8] = {0,0,0,0,0,0,0,0}; double Ddata = 12.66; Double_HEX(Ddata,data); for(int i=0;i<8;i++) printf("0x%X\n",data[i]); return 0; }
三、十六进制(HEX) 转 浮点数
1. 十六进制(HEX) 转 单精度(float)
具体代码如下:
int main(int argc, char *argv[]) { char data[4] = {0x5C,0x8F,0x4A,0x41}; float fdata = 0; memcpy(&fdata,data,sizeof(fdata)); printf("fdata=%f\n",fdata); return 0; }
2. 十六进制(HEX) 转 双精度(double)
具体代码如下:
int main(int argc, char *argv[]) { char data[8] = {0x52,0xB8,0x1E,0x85,0xEB,0x51,0x29,0x40}; double Ddata = 0; memcpy(&Ddata,data,sizeof(Ddata)); printf("Ddata=%f\n",Ddata); return 0; }
链接:https://blog.csdn.net/MQ0522/article/details/126394428
标签:十六进制,hdata,单精度,int,浮点数,unsigned,char,fdata,Ddata 来源: https://www.cnblogs.com/mokongking/p/16671196.html