位元組和float int相互轉換

來源:互聯網
上載者:User

串列通訊是以位元組為單位進行傳送的,對於浮點數和整型數都需要進行轉換位元組數組才能進行通訊。

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;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.