casting - C Function to Convert float to byte array -
i'm trying make function accept float variable , convert byte array. found snippet of code works, reuse in function if possible.
i'm working arduino environment, understand accepts c language.
currently works:
float_variable = 1.11; byte bytes_array[4]; *((float *)bytes_array) = float_variable;
what can change here make function work?
float float_test = 1.11; byte bytes[4]; // calling function float2bytes(&bytes,float_test); // function void float2bytes(byte* bytes_temp[4],float float_variable){ *(float*)bytes_temp = float_variable; }
i'm not familiar pointers , such, read (float) using casting or something?
any appreciated!
cheers
*edit: solved
here's final function works in arduino finds this. there more efficient solutions in answers below, think okay understand.
function: converts input float variable byte array
void float2bytes(float val,byte* bytes_array){ // create union of shared memory space union { float float_variable; byte temp_array[4]; } u; // overite bytes of union float variable u.float_variable = val; // assign bytes input array memcpy(bytes_array, u.temp_array, 4); }
calling function
float float_example = 1.11; byte bytes[4]; float2bytes(float_example,&bytes[0]);
thanks everyone's help, i've learnt pointers , referencing in past 20 minutes, cheers stack overflow!
easiest make union:
#include <stdio.h> int main(void) { int ii; union { float a; unsigned char bytes[4]; } thing; thing.a = 1.234; (ii=0; ii<4; ii++) printf ("byte %d %02x\n", ii, thing.bytes[ii]); return 0; }
output:
byte 0 b6 byte 1 f3 byte 2 9d byte 3 3f
note - there no guarantee byte order… depends on machine architecture.
to function work, 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 hack it:
void float2bytes(byte* bytes_temp[4],float float_variable){ memcpy(bytes_temp, (unsigned char*) (&float_variable), 4); }
note - in either case make sure copy data location given input parameter. crucial, local variables not exist after return (although declare them static
, let's not teach bad habits. if function gets called again…)
Comments
Post a Comment