遗忘海岸

江湖程序员 -Feiph(LM战士)

导航

浮点数转byte数组

  long a=123451;
  float b=34.56745f;
  float c=0.0;
  
   byte fbs[]={0,0,0,0};
   byte* t=fbs;
   float2Bytes(t,b);
   unsigned int addrF=(unsigned int) &b;
   unsigned int addrFc=(unsigned int) &c;

 

Serial.println(addrF);
  Serial.println(addrFc);
  float x= bytes2Float(fbs);
   
   for(int i=0;i<4;i++){
   byte bf1=*((byte*)(addrF + i));
   *((byte*)(addrFc + i))=bf1;
     Serial.print(bf1,HEX);
     if(i<3)  Serial.print("-");
   }
   Serial.println(" ");
   
  for(int j=0;j<4;j++){
    Serial.print(fbs[j],HEX);
    if(j<3)Serial.print("-");

  }
  Serial.println(" ");
  Serial.print("c:");
  Serial.println(c,6);
 
  Serial.print("x:");
  Serial.println(x,6);
  
  Serial.println(sizeof(b));
View Code

 

 

void float2Bytes(byte bytes_temp[4],float float_variable){ 
  union {
    float a;
    byte bytes[4];
  } thing;
  thing.a = float_variable;
  memcpy(bytes_temp, thing.bytes, 4);
}


float bytes2Float(byte bytes_temp[4]){ 
  union {
    float a;
    byte bytes[4];
  } thing;
 
  memcpy(thing.bytes,bytes_temp,  4);
  return thing.a;
}

//查找字节数组中是否以指定的字符串开头
boolean bStartsWith(byte data[],int len, String fStr){
    int fLen=fStr.length() ;
   byte fBytes[fLen + 1];
   fStr.getBytes(fBytes,fLen+1);

   if(len<=0)return false;
   if(len<fLen)return false;
   byte flag=1;
   for(int j=0;j<fLen;j++){
       if(fBytes[j]!=data[j])
       {
                flag=0;
                break; 
        }
              
    }
   if(flag) return true; 
  
   return false;
}

 void long2byte(unsigned long res,byte targets[] ) {  
        targets[0] = (byte) (res & 0xff);
        targets[1] = (byte) ((res >> 8) & 0xff);
        targets[2] = (byte) ((res >> 16) & 0xff);
        targets[3] = (byte) (res >> 24);
              
    }  
    
unsigned long bytes2long(byte buf[]) {  
        unsigned long firstByte = 0;  
        unsigned long secondByte = 0;  
        unsigned long thirdByte = 0;  
        unsigned long fourthByte = 0;  
        int index = 0;  
        firstByte = (0x000000FFU & ( buf[index+3]));  
        secondByte = (0x000000FFU & ( buf[index + 2]));  
        thirdByte = (0x000000FFU & ( buf[index + 1]));  
        fourthByte = (0x000000FFU & ( buf[index ]));  
        index = index + 4;  
        return ((unsigned long) (firstByte << 24 | secondByte << 16 | thirdByte << 8 | fourthByte)) & 0xFFFFFFFFUL;  
    }  
View Code

 

int array[13];

int * addrArr=array; //数组可以看成int类型的地址

 

arduino 发送float类型数据

float b=(float)millis() / 1000.0;


Serial2.write( ((byte*) &b),4);
//Serial2.flush();
delay(100);

posted on 2016-04-14 16:28  遗忘海岸  阅读(2302)  评论(0编辑  收藏  举报