This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Initialize a const floating point with an raw binary value

Hello,

is there a way to initialize a floating point constant (code memory) with a raw binary value? Because we use a few special NAN flags and I cant initialize them using the CX51 compilier. With the IAR compilier I used a union and specified if the value should be interpreted as integer or floating point but with the CX51 compilier this is not possible for constant values because the compilier does not support this kind of initialization. It is part of C99 Standard but CX51 is C90. Maybe there is another way to do this.

Best regards

Parents
  • The union hack, while easier to control in C99, is also possible in C90.  All you have to do is fix the order of element declarations in the union such that the one you're actually going to initialize comes first:

    union hack {
      uint8_t bytes[sizeof float];
      float val
    };
    
    const union hack hackedval = {{1, 2, 3, 4}};

    For similar information, you could have just looked up 'nan' in the C51 documentation.

    That said, this union hack is quite rightfully frowned upon in civilized code (and outright forbidden in most industry coding rules).  On top of that for the particular case at hand it's most likely pointless anyway, because there's very little chance that NaN handling with all its traps and pitfalls fully works in C51, which has to do it all in software, so it does have to cut some corners to arrive at anything resembling useful performance.

Reply
  • The union hack, while easier to control in C99, is also possible in C90.  All you have to do is fix the order of element declarations in the union such that the one you're actually going to initialize comes first:

    union hack {
      uint8_t bytes[sizeof float];
      float val
    };
    
    const union hack hackedval = {{1, 2, 3, 4}};

    For similar information, you could have just looked up 'nan' in the C51 documentation.

    That said, this union hack is quite rightfully frowned upon in civilized code (and outright forbidden in most industry coding rules).  On top of that for the particular case at hand it's most likely pointless anyway, because there's very little chance that NaN handling with all its traps and pitfalls fully works in C51, which has to do it all in software, so it does have to cut some corners to arrive at anything resembling useful performance.

Children