java中float与int转化有int i = Float.floatToIntBits(v);及相反函数,相当方便;
下面介绍的是C++中
c++ float int 按位互转
inline float int32_bitcast_float32(int temp){return(*((float *)((void *)(&temp))));}inline int float32_bitcast_int32(float temp){return(*((int *)((void *)(&temp))));}
字节和float int相互转换
串行通讯是以字节为单位进行传送的,对于浮点数和整型数都需要进行转换字节数组才能进行通讯。
MCU和PC的浮点数都是基于IEEE754格式的。有4字节(float)、8字节(double)、10字节(有一些不支持)。这里以4字节(float)浮点数为例。
转化常见的方法有:
一、强制指针类型转换。
// 转换Int数据到字节数组
unsigned int intVariable,i;
unsigned char charArray[2];
(unsigned char) * pdata = ((unsigned char)*)&intVariable; //进行指针的强制转换
for(i=0;i<2;i++)
{
charArray[i] = *pdata++;
}
// 转换float数据到字节数组
unsigned int i;
float floatVariable;
unsigned char charArray[4];
(unsigned char) * pdata = ((unsigned char)*)&floatVariable; //进行指针的强制转换
for(i=0;i<4;i++)
{
charArray[i] = *pdata++;
}
// 转换字节数组到int数据
unsigned int intVariable="0";
unsigned char i;
void *pf;
pf =&intVariable;
(unsigned char) * px = charArray;
for(i=0;i<2;i++)
{
*(((unsigned char)*)pf+i)=*(px+i);
}
// 转换字节数组到float数据
float floatVariable="0";
unsigned char i;
void *pf;
pf =&floatVariable;
(unsigned char) * px = charArray;
for(i=0;i<4;i++)
{
*(((unsigned char)*)pf+i)=*(px+i);
}
二、使用结构和联合
定义结构和联合如下
typedef union {struct {unsigned char low_byte;
unsigned char mlow_byte;
unsigned char mhigh_byte;
unsigned char high_byte;
}float_byte;
struct {unsigned int low_word;
unsigned int high_word;
}float_word;
float value;
}FLOAT;
typedef union {
struct {
unsigned char low_byte;
unsigned char high_byte;
} d1;
unsigned int value;
} INT;
使用方法:
对于浮点数:
FLOAT floatVariable;在程序中直接使用floatVariable.float_byte.high_byte,floatVariable.float_byte.mhigh_byte,
floatVariable.float_byte.mlow_byte,floatVariable.float_byte.low_byte这四个字节就可以方便的进行转换了。
例子:
main()
{
unsigned char c[]={0x80,0xDA,0xCC,0x41};//四个字节顺序颠倒一下赋值
FLOAT x;
x.float_byte.high_byte=0x41;
x.float_byte.mhigh_byte=0xCC;
x.float_byte.mlow_byte=0xDA;
x.float_byte.low_byte=0x80;
printf("%f/n",x.value);//25.607
}
对于整数:
INT intVariable;在程序中直接使用intVariable.value.high_byte,intVariable.value.low_byte就OK了。
三、对整型数可以用数学运算的方法进行转换
unsigned int intVariable;
unsigned char low_byte = intVariable%256;
unsigned char high_byte = intVariable/256;
=================================================
关于字节还原成float还有另一种方法:
先把那四个字节包装成 int,然后再对该 int 进行转换(程序假设 int 是 32-bit 数据): #include <stdio.h> #include <math.h> /* C 什么时候才会像 Java 那样提供 byte 数据类型? 算了。 我们自己来吧 */ typedef unsigned char byte; int fourBytesToInt( byte b1, byte b2, byte b3, byte b4 ) { return ( b1 << 24 ) + ( b2 << 16 ) + ( b3 << 8 ) + b4; } float intBitsToFloat( int bits ) { /* s 为符号(sign);e 为指数(exponent);m 为有效位数(mantissa)*/ int s = ( bits >> 31 ) == 0 ? 1 : -1, e = ( bits >> 23 ) & 0xff, m = ( e == 0 ) ? ( bits & 0x7fffff ) << 1 : ( bits & 0x7fffff ) | 0x800000; return s * m * ( float ) pow( 2, e - 150 ); } void main( ) { printf( "%f", intBitsToFloat( fourBytesToInt( 64, 78, 249, 219 ) ) ); }另外一篇关于IEEE754标准中float型存储方式的相关文章:
http://chuansu.iteye.com/blog/1484917