Zaya
Zaya

Reputation: 336

How to manipulate floats on a bit level in C

Is there a way to convert a float to just a bit-pattern so that I can do things like

int mantissa = 0u;
int exponent = 0u;    

mantissa = myFloat>>11;
exponent = myFloat>>23;

Attempting to do this generates a compile-time error:

main.c:24:11: error: invalid operands to binary >> (have 'float' and 'int')
mantissa = (myFloat>>11); 

main.c:25:12: error: invalid operands to binary >> (have 'float' and 'int')
exponent = (myFloat>>23);

Is there a way to do this? Converting to int will give the bit pattern of the signed int version, so I don't want to do that, I want the bits of the original float saved into an unsigned int. How can I best do this

Upvotes: 1

Views: 515

Answers (1)

C_Elegans
C_Elegans

Reputation: 1133

the typical solution is something like this:

typedef union {
  unsigned int i;
  float f;
} u;
u u1;
u1.f = 0.341; // your float here
unsigned int x = u1.i; // converted to uint

This legal in C99 and does not invoke UB (which is good), or violate strict aliasing rules.

Upvotes: 2

Related Questions