Search code examples
cembeddedtype-punning

Reassemble float from bytes inline


I'm working with HiTech PICC32 on the PIC32MX series of microprocessors, but I think this question is general enough for anyone knowledgable in C. (This is almost equivalent to C90, with sizeof(int) = sizeof(long) = sizeof(float) = 4.)

Let's say I read a 4-byte word of data that represents a float. I can quickly convert it to its actual float value with:

#define FLOAT_FROM_WORD(WORD_VALUE) (*((float*) &(WORD_VALUE)))

But this only works for lvalues. I can't, for example, use this on a function return value like:

FLOAT_FROM_WORD(eeprom_read_word(addr));

Is there a short and sweet way to do this inline, i.e. without a function call or temp variable? To be honest, there's no HUGE reason for me to avoid a function call or extra var, but it's bugging me. There must be a way I'm missing.

Added: I didn't realise that WORD was actually a common typedef. I've changed the name of the macro argument to avoid confusion.


Solution

  • You can run the trick the other way for return values

    float fl;
    *(int*)&fl = eeprom_read_word(addr);
    

    or

    #define WORD_TO_FLOAT(f)  (*(int*)&(f))
    
    WORD_TO_FLOAT(fl) = eeprom_read_word(addr);
    

    or as R Samuel Klatchko suggests

    #define  ASTYPE(type, val) (*(type*)&(val))
    ASTYPE(WORD,fl) = eeprom_read_word(addr);