How to convert or cast a float into its bit sequence such as a long

前端 未结 5 721
死守一世寂寞
死守一世寂寞 2021-01-13 02:24

Good day, I am working in a 16-bit C environment, and I want to convert a float value into its bit sequence such as an integer value. There are multiple ways I know how to a

5条回答
  •  生来不讨喜
    2021-01-13 02:59

    You can do this by type-punning through an anonymous union:

    unsigned int i = ((union { float f; unsigned int i; }){5.0}).i;
    

    Note that this initialiser is not a constant expression and so cannot be used at file scope.

    Type-punning through a union is specified to be allowed by the standard in a footnote:

    c11

    6.5.2.3 Structure and union members

    95) If the member used to read the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type as described in 6.2.6 (a process sometimes called ‘‘type punning’’). This might be a trap representation.

    From a practical point of view, although you cannot use this method to initialise a file-scope constant, you could write an initialisation function that loads the values into file-scope variables at program or module initialisation time.

    You're not going to find a portable method that allows you to calculate the values as a compile-time constant expression, because the object representations covered by section 6.2.6 of the standard only apply at run time. Otherwise, a cross-compiler would be required to simulate and not just parametrise the execution environment of its target.


    Addendum: this is valid C++, with the condition that the union type must be named:

    union u { float f; unsigned int i; };
    unsigned int i = u{5.0}.i;
    

    So if you're willing to write in hybrid C/C++ and compile with a C++ compiler, then you can perform the cast at compile time.

提交回复
热议问题