C Function to Convert float to byte array

后端 未结 6 900
天命终不由人
天命终不由人 2020-12-04 22:42

I\'m trying to make a function that will accept a float variable and convert it into a byte array. I found a snippet of code that works, but would like to reuse it in a func

6条回答
  •  粉色の甜心
    2020-12-04 23:01

    Easiest is to make a union:

    #include 
    
    int main(void) {
      int ii;
      union {
        float a;
        unsigned char bytes[4];
      } thing;
    
      thing.a = 1.234;
      for (ii=0; ii<4; ii++) 
        printf ("byte %d is %02x\n", ii, thing.bytes[ii]);
      return 0;
    }
    

    Output:

    byte 0 is b6
    byte 1 is f3
    byte 2 is 9d
    byte 3 is 3f
    

    Note - there is no guarantee about the byte order… it depends on your machine architecture.

    To get your function to work, do this:

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

    Or to really hack it:

    void float2Bytes(byte bytes_temp[4],float float_variable){ 
      memcpy(bytes_temp, (unsigned char*) (&float_variable), 4);
    }
    

    Note - in either case I make sure to copy the data to the location given as the input parameter. This is crucial, as local variables will not exist after you return (although you could declare them static, but let's not teach you bad habits. What if the function gets called again…)

提交回复
热议问题