I want to convert a float into an array of bytes (char) to transmit over a non-canonical serial connection. I want to use the 4 byte structure of the original float that way I do not have to worry about variable lengths and still get full precision.
One method I have stumbled upon is this CCS compiler FAQ but I would like to try to get my approach (already implemented) working before I redo the code. Especially since I'm not sure if the PIC C compiler works the same as the ARM Linux gcc compiler in this scenario.
I attempted to use a union to do the conversion like so:
Code:
union
{
char bytes[4];
float val;
} bfconvert;
float bobsuruncle = 7.314239;
char output[4];
bfconvert.val = bobsuruncle;
output[0] = bytes[0];
output[1] = bytes[1];
output[2] = bytes[2];
output[3] = bytes[3];
on the other side of the serial line I perform the opposite process:
Code:
union
{
char bytes[4];
float val;
} bfconvert;
float whosuruncle;
char input[4];
// Read bytes off serial connection
bfconvert.bytes[0] = input[0];
bfconvert.bytes[1] = input[1];
bfconvert.bytes[2] = input[2];
bfconvert.bytes[3] = input[3];
whosuruncle = bfconvert.val;
The resulting output varies wildly with small changes in the actual float value (I don't have any examples off hand unfortunately). The best example I can give is that a value that should be very close to zero (no higher than 0.1, but generally lower) comes out as:
680667722740137984.000000
Thanks in advance,
osuee