#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
union floattestA //使用共享内存把字节数组转为float
{
float _FLOAT; //_FLOAT与4个char共用内存
struct
{
char s0;
char s1;
char s2;
char s3;
};
} f;
// num 类型占字节数
// 1 字符
// 2 整型
// 4 浮点
float ByteToFloat(unsigned char *ucBuff,int num) //正确
{
switch (num)
{
case 1:
return (float)(*((unsigned char*)ucBuff));
case 2:
return (float)((((unsigned short) (ucBuff[0] & 0xFF) << 8) | (unsigned short) (ucBuff[1] & 0xFF)));
case 4:
f.s0=ucBuff[0];
f.s1=ucBuff[1];
f.s2=ucBuff[2];
f.s3=ucBuff[3];
return f._FLOAT;
default:
return (float)(*((float*)ucBuff));
}
}
// 1 字符
// 2 整型
// 4 浮点
float ByteToFloat2(unsigned char *ucBuff,int num) //arm linux报bus error
{
switch (num)
{
case 1:
return (float)(*((unsigned char*)ucBuff));
case 2:
return (float)((((unsigned short) (ucBuff[0] & 0xFF) << 8) | (unsigned short) (ucBuff[1] & 0xFF)));
case 4:
return (float)(*((float*)ucBuff));
default:
return (float)(*((float*)ucBuff));
}
}
void main(void)
{
unsigned char array[]={0x4D ,0x3C ,0x48 ,0x42};
f.s0 = array[0];
f.s1 = array[1];
f.s2 = array[2];
f.s3 = array[3];
//a._FLOAT=(float)12.751234;
//printf("0x%x,0x%x,0x%x,0x%x\n",a.s0,a.s1,a.s2,a.s3);
//a.s0 = 0x0e;
//a.s1 = 0x05;
//a.s2 = 0x4c;
//a.s3 = 0x41;
printf("float value : %f\n",f._FLOAT);
printf("ByteToFloat2:%f\n",ByteToFloat(array,4));
}