Jump to content
  • Advertisement
Sign in to follow this  
Yratelev

[.net] Extracting mantissa out of float

This topic is 4938 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
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!