Bit Copy Typing

I want type a to floatbe like int. However, this is not bitwise copying. Is it possible to cast floatto intwhile saving all bits (sign, exponent, mantissa)?

+5
source share
3 answers

Most languages ​​allow something like this, in C it looks like:

float f = 3.14f;
int i = *(int*)&f;
+3
source

This cannot be done completely in a C-compatible way, but you can use unions:

union{
    int i;
    float f;
} u;

u.f = 123.456;  //  Your value.

//  Read u.i.

Today, this should work on almost all systems. And, of course, it is assumed that floatthey inthave the same size.

, , , undefined.


(, - . ) memcpy():

int i;
float f;

f = 123.456;  //  Your value.

memcpy(&i, &f, sizeof(int));

//  Read i
+4

You can use union .

union
{
    int tmp;
    float f;
} u;

u.f = z;

Then u.tmpthese are the same bits. (Code taken from this Wikipedia article ).

+2
source

All Articles