關於float型資料與int型,位元組陣列的轉化
阿新 • • 發佈:2019-01-08
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 ) ) ); }