How to convert or distinguish float into your own bit sequence, such as long

Good afternoon, I am working in a 16-bit C environment, and I want to convert the float value to its bit sequence, such as an integer value. There are several ways that I know how to achieve this, one with union; eg:

union ConvertFloatToInt
{  
   float input;  
   unsigned long  output;  
};

it "converts" floating values ​​to a long value by reading the same memory area, simply interpreting it differently.

union ConvertFloatToInt x;
x.input = 20.00;

result

x.output = 0x41A00000;

Other methods are void pointer casts ...

float input = 40.00;
unsigned long output;
void* ptr;
ptr = &input;
output = *(unsigned long*) ptr;

result

output = 0x42200000;

This is the idea of ​​what I'm trying to do, however, I want the compiler to do the conversion for me at build time, and not at run time.

I need to insert the converted floating data into a constant (const) unsigned long.

float , unsigned long. - : ( , , )

const unsigned long FloatValue = (unsigned long) ((void) ((float) 20.654));

? , , - void, void, , , const.

Edit

C90. .

, , . , .

, , , . . , , ( - , C90)

, : gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3

typedef union
{
            float myfloat;
            unsigned long mylong;
} custom_type;

typedef struct
{
            int a;
            int b;
            custom_type typeA;
            custom_type typeB;
} my_struct;

const my_struct myobj =
{
                            1,2,3.84F,4
};

int main(void)
{
            printf(":: %f\n", myobj.typeA.myfloat);
            printf(":: %ul\n", myobj.typeA.mylong);
            return 0;
}

:: 3.840000
:: 1081459343l

, ( ).

+5
5

:

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

, .

-punning :

6.5.2.3

95) , , , , , 6.2.6 (, "" ). .

, , , .

, , , 6.2.6 , . , .


: ++, , union :

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

, C/++ ++, .

+5

C99:

const unsigned long FloatValue =
        *(unsigned long *) &(float) {20.654f};

, , FloatValue , .

+1

, float , , - . cut'n'paste .

, script C.

+1

, float, :

const float _FloatValue = 20.654;
#define FloatValueL *((unsigned long *) &_FloatValue)
0

All Articles