Technical Support

GENERAL: BYTE-WISE ACCESS TO FLOAT VALUES


Information in this article applies to:

  • C51 All Versions
  • C166 All Versions
  • CARM All Versions
  • C251 All Versions

QUESTION

I must store floating point values into an EEPROM space that is byte-wise accessed via I2C BUS. How can I split a float value into individual bytes?

ANSWER

One approach is to use a union that stores the float value along with a unsigned char array. For example:

union v  {
  float         f;
  unsigned char uc[4];
};

union v val;
float f;

extern void store_byte (unsigned char v);

void test (void)  {
  val.f = 34.567;           // set floating point value
  store_byte (val.uc[0]);   // write access to the bytes of the float value
  store_byte (val.uc[1]);
  store_byte (val.uc[2]);
  store_byte (val.uc[3]);

  val.uc[0] = 0x3F;         // set float value (1.1)
  val.uc[1] = 0x8C;
  val.uc[2] = 0xCC;
  val.uc[3] = 0xCD;
  f = val.f;                // read the value as FLOAT type.
}

MORE INFORMATION

SEE ALSO

FORUM THREADS

The following Discussion Forum threads may provide information related to this topic.

Last Reviewed: Friday, July 15, 2005


Did this article provide the answer you needed?
 
Yes
No
Not Sure