floa、int与字节数组的转化(IEEE754)
(2017-05-04 16:16:07)
标签:
软件ieee754float |
分类: 硬件大类 |
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
字节和float int相互转换
串行通讯是以字节为单位进行传送的,对于浮点数和整型数都需要进行转换字节数组才能进行通讯。
MCU和PC的浮点数都是基于IEEE754格式的。有4字节(float)、8字节(double)、10字节(有一些不支持)。这里以4字节(float)浮点数为例。
转化常见的方法有:
一、强制指针类型转换。
unsigned int intVariable,i;
unsigned char charArray[2];
(unsigned char) * pdata = ((unsigned char)*)&intVariable;
for(i=0;i<2;i++)
{
}
//
unsigned int i;
float floatVariable;
unsigned char charArray[4];
(unsigned char) * pdata = ((unsigned char)*)&floatVariable;
for(i=0;i<4;i++)
{
}
//
unsigned int
unsigned char
void
pf
(unsigned char) * px = charArray;
for(i=0;i<2;i++)
{
}
//
float
unsigned char
void
pf
(unsigned char) * px = charArray;
for(i=0;i<4;i++)
{
}
二、使用结构和联合
定义结构和联合如下
typedef union {struct {unsigned char low_byte;
typedef union
使用方法:
对于浮点数:
FLOAT floatVariable;在程序中直接使用floatVariable.float_byte.high_byte,floatVariable.float_byte.mhigh_byte,
floatVariable.float_byte.mlow_byte,floatVariable.float_byte.low_byte这四个字节就可以方便的进行转换了。
例子:
main()
{
}
对于整数:
INT intVariable;在程序中直接使用intVariable.value.high_byte,intVariable.value.low_byte就OK了。
三、对整型数可以用数学运算的方法进行转换
unsigned int intVariable;
unsigned char low_byte = intVariable%6;
unsigned char high_byte = intVariable/256;
=================================================
关于字节还原成float还有另一种方法:
先把那四个字节包装成 int,然后再对该 int 进行转换(程序假设 int 是 32-bit 数据): #include #include <<a target="_blank" class="inner-link decor-none" href="http://zhidao.baidu.com/search?word=math.h&fr=qb_search_exp&ie=utf8" rel="nofollow" style="color: rgb(45, 100, 179); text-decoration: none;">math.h> typedef unsigned char byte; int fourBytesToInt( byte b1, byte b2, byte b3, byte b4 ) {另外一篇关于IEEE754标准中float型存储方式的相关文章:return ( b1 << 24 ) + ( b2 << 16 ) + ( b3 << 8 ) + b4; } float intBitsToFloat( int bits ) { 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 ) ) ); }
http://chuansu.iteye.com/blog/1484917 http://blog.csdn.net/jocks/article/details/7800861
浮点转4字节工具:https://www.h-schmidt.net/FloatConverter/IEEE754.html
inter和motorola格式
前一篇:焊锡线(焊锡丝)简介:
后一篇:MPU6050的DMP移植