C Function to Convert float to byte array

后端 未结 6 911
天命终不由人
天命终不由人 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:11

    Although the other answers show how to accomplish this using a union, you can use this to implement the function you want like this:

    byte[] float2Bytes(float val)
    {
        my_union *u = malloc(sizeof(my_union));
        u->float_variable = val;
        return u->bytes_array;
    }
    

    or

    void float2Bytes(byte* bytes_array, float val)
    {
        my_union u;
        u.float_variable = val;
        memcpy(bytes_array, u.bytes_array, 4);
    }
    

提交回复
热议问题