由于在部分开发编译器中,无法使用float型数据,在单片机中取float型数据的整数部分和小数部分有点麻烦,
在网上看了别的兄弟代码,自己改下了下,测试还可以用。
typedef struct __buf_to_float_
{
int inter_part;
int decimal;
int sig;
}float_data;
char bufx[4] = {0x43,0x6a,0x00,0x00};
float_data buf_to_Float_get(char *bufx)
{
int FloatValue = 0;
float_data ret;
int Exp;
int FloatPath;
int MantissaPart;
ret.sig = 1;
FloatValue |= bufx[0]<<24;
FloatValue |= bufx[1]<<16;
FloatValue |= bufx[2]<<8;
FloatValue |= bufx[3];
if(FloatValue&0x80000000) //最高位为符号位
{
ret.sig = -1;
}
Exp = (FloatValue>>23)&0xff; //取得指数字段,一个字节。第二到第9字节
MantissaPart=(FloatValue&0x7fffff)|0x800000;//尾数字段,23位加一个默认位,共24位。
ret.inter_part = (MantissaPart>>(150-Exp));
FloatPath = MantissaPart&(0xffffff>>(Exp-126));//取得小数部分
ret.decimal = FloatPath/float(1<<(150-Exp));
return ret;
}
int main(void)
{
float_data ret;
ret = buf_to_Float_get(bufx);
printf("\n符号:=%d 整数部分 =%d,小数部分=%d\n",ret.sig,ret.inter_part,ret.decimal);
return 0;
}
//
下面做一次修改:上面的版本存在问题,不能有float,不是所有的编译器都支持float;
#include<stdio.h>
#define BitSet(Number,pos) ((Number) &= ~(1<<(pos)))
#define BitGet(Number,pos) ((Number) >> (pos)&1)
typedef struct float_data_struct
{
int sig;
int inter_part;
int decimal;
}float_data;
#define FLOAT_VALUE 10000000
float_data float_binary_to_struct(char *bufx)
{
int i;
int exp;
int exp_sig;
int inter = 0;
int descimal;
int descimal_data;
int data = 0;
int flag;
float_data ret;
unsigned int FloatValue = 0;
FloatValue |= ((bufx[0]<<24)&0xff000000);
FloatValue |= ((bufx[1]<<16) & 0xff0000);
FloatValue |= ((bufx[2]<<8) & 0xff00);
FloatValue |= (bufx[3] & 0xff);
exp = ((((FloatValue & 0x7f800000)>>23)&0xff)-127);
if(exp < 0)
{
exp_sig = -1;
}
else
{
exp_sig = 1;
}
if(FloatValue&(1<<31))
{
ret.sig = -1;
}
else
{
ret.sig = 0;
}
descimal = ((FloatValue & 0x7fffff));
descimal_data = 0;
for(i=0; i<23;i++)
{
if(BitGet(descimal, 22-i))
{
data = (FLOAT_VALUE / (1<<(i+1)));
}
else
{
data = 0;
}
descimal_data += data;
}
descimal_data +=(FLOAT_VALUE);
if(exp > 0)
{
descimal_data =descimal_data*(1<<exp);
}
else
{
exp *= (-1);
descimal_data =descimal_data/(1<<exp);
}
ret.decimal = (descimal_data%FLOAT_VALUE)/(FLOAT_VALUE/1000);
flag = ret.decimal%10;
if(flag >=5 )//此处进行了四舍五入
{
ret.decimal=(ret.decimal/10+1);
}
else
{
ret.decimal=(ret.decimal/10);
}
ret.inter_part = descimal_data/FLOAT_VALUE;
return ret;
}
void main(void)
{
//char buf[4]={0x40,0x88,0x2d,0xe0};//3FA00000
//char buf[4]={0xe0,0x2d,0x88,0x40};
//char buf[4]={0x42,0xc9,0x22,0xb6};//3FA00000'
//char buf[4]={0xBE,0x23,0xD7,0x0A};//BE23D70A' -0.16
//char buf[4]={0xBD,0x75,0xC2,0x88};//BD75C288' -0.06
//char buf[4]={0xC1,0x80,0x7A,0xE1};//C1807AE1 -16.06
//char buf[4]={0,0,0,0};//000000000 0
//char buf[4]={0x3F,0x93,0x33,0x33};//3F933333 1.15
//char buf[4]={0x3E,0x57,0x0A,0x3C};//3E570A3C 0.21
//char buf[4]={0x41,0x43,0x5c,0x28};//41435C28 12.21
char buf[4]={0x42,0xCC,0x0F,0x5C};//42CC0F5C 102.03
float_data ret;
ret = float_binary_to_struct(buf);
printf("sig:%d, decimal:%d,inter:%d\n", ret.sig, ret.decimal, ret.inter_part);
return ;
}