• Advertisement
Sign in to follow this  

[.net] Extracting mantissa out of float

This topic is 4849 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, in C# how can i get the mantissa bit pattern from a float uint a = (f & 0x007fffff); wont compile because operator & cant be applied to a float. Cheers Yratelev

Share this post


Link to post
Share on other sites
Advertisement
Converting a float to an int by preserving bit pattern:
float f = (some float number);
unsigned int i = *(int*) &f;

Now you can just use the bitwise stuff to get whichever part of the float you want.

[EDIT] Oh, it's C#...eh, not sure if what I wrote is valid without using an unsafe block.

Share this post


Link to post
Share on other sites
Quote:
Original post by Promit
Converting a float to an int by preserving bit pattern:
float f = (some float number);
unsigned int i = *(int*) &f;

Now you can just use the bitwise stuff to get whichever part of the float you want.

[EDIT] Oh, it's C#...eh, not sure if what I wrote is valid without using an unsafe block.

wouldn't it be safer to use a union of a float and an int?

Share this post


Link to post
Share on other sites
Quote:
Original post by capn_midnight
Quote:
Original post by Promit
Converting a float to an int by preserving bit pattern:
float f = (some float number);
unsigned int i = *(int*) &f;

Now you can just use the bitwise stuff to get whichever part of the float you want.

[EDIT] Oh, it's C#...eh, not sure if what I wrote is valid without using an unsafe block.

wouldn't it be safer to use a union of a float and an int?

C# doesn't have unions. A list of C# keywords is here. You can use the FixedLayout attribute to emulate them, though.

Share this post


Link to post
Share on other sites
Quote:
Original post by RipTorn

float f=...;

int i = System.BitConverter.ToInt32( System.BitConverter.GetBytes(f) , 0) & 0x007fffff;

That looks good but will it be much slower than the unsafe version?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement