Modify floats' bits

Hi!

By academic purpouses I want to show to my students real runnable examples about floating point convetion (IEEE754), but for that i need to use logic bitwise operations on floats.

Is there a way to do it in rust like in c using:

float x = 5.4;
unsigned int x_as_bits = *((unsigned int*)&x);   // pick x's pointer and cast
                                                 // it as other type pointer, then, deferenciate it~

Thanks!

Use f32::to_bits and f32::from_bits.

4 Likes

By the way, you shouldn't do type punning in C like that because it is UB.
The correct way to do is using memcpy. It will be perfectly optimized.

float x = 5.4f;
uint32_t y;
memcpy(&y, &x, sizeof(uint32_t));
8 Likes

Thanks you for both answers! :heart::heart:

1 Like