#include "stdio.h"
#define uint8_t unsigned char
#define uint16_t unsigned short
#define uint32_t unsigned int
uint32_t Float_To_Hex(float data)
{
uint32_t Hex_Data = 0;
uint32_t F1 = 0;//尾数
uint8_t F2 = 0;//阶码
uint8_t F3 = 0;//符号位
uint8_t i = 0;
char a = 0; //整数位数
float F_c = 0;
uint32_t F_a = 0,F_b = 0;
if(data == 0)
return 0;
if(data<0)
{
F3 = 1;
data = -data;
}
F_a = (int)data;
F_c = data - F_a;
for(i=0;i<32;i++)
{
if(F_a == 0)
{
a = 0;
break;
}
if((F_a << i) & 0x40000000)
{
a = 30 - i;
break;
}
}
F2 = 127 + a ;
for(i=0;i<23-a;i++)
{
F_c = F_c * 2;
if(F_c < 1)
F_a = (F_a << 1);
else if(F_c >= 1)
{
F_c = F_c - 1;
F_a = (F_a << 1) | 1;
if(a == 0)
{
a = -i-1;
F2 = 127 - (i+1);
}
}
}
F1 = F_a & 0x007FFFFF;
if(F3 == 1)
Hex_Data = Hex_Data | 0x80000000;
Hex_Data = Hex_Data | (F2 << 23);
Hex_Data = Hex_Data | F1;
printf("尾数:%8x\n",F1);
printf("指数:%8x\n",F2);
printf("符号位:%8x\n",F3);
return Hex_Data;
}
void main(void)
{
float a = 0;
uint32_t b = 0;
while(1)
{
printf("请输入一个浮点数\n");
scanf("%f",&a);
b = Float_To_Hex(a);
printf("Hex数据:%8x\n",b);
}
}