Convert float to bytes

union {
	float f;
	uint8_t ui8[4];
	//uint32_t ui32;			//<<Could also use if you wanted
} MyFloatBytesUnionValue;

	MyFloatBytesUnionValue.f = 1.234;
	for (Index = 0; Index < 4; Index++) 
		printf ("byte %d is %02x\n", Index, MyFloatBytesUnionValue.ui8[Index]);

Convert bytes to float

union {
	float f;
	uint8_t ui8[4];
	//uint32_t ui32;			//<<Could also use if you wanted
} MyFloatBytesUnionValue;

	MyFloatBytesUnionValue.ui8[3] = 0x1f;
	MyFloatBytesUnionValue.ui8[2] = 0x85;
	MyFloatBytesUnionValue.ui8[1] = 0x45;
	MyFloatBytesUnionValue.ui8[0] = 0x41;

	//Or you could do this:
	//MyFloatBytesUnionValue.ui32 = ((uint32_t)byte_value[3] << 24) | ((uint32_t)byte_value[2] << 16) | ((uint32_t)byte_value[1] << 8) | (uint32_t)byte_value[0];

	printf ("float is %f\n", MyFloatBytesUnionValue.f);

Note, if this appears not to work (you get zero out but with a valid float value in) then try reversing the byte order!

Example

The following input bytes 0x1f, 0x85, 0x45, 0x41 will produce a float output of 12.345

USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through resources like this. We hope you find it helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support here. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published. Required fields are marked *