[.net] Extracting mantissa out of float

Started by
12 comments, last by capn_midnight 19 years, 3 months ago
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
Yratelev
Advertisement
If you don't need the floating value, you could try converting it to uint or int.
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.
SlimDX | Ventspace Blog | Twitter | Diverse teams make better games. I am currently hiring capable C++ engine developers in Baltimore, MD.
You need better Google skills.

The very first hit has the code you need.
enum Bool { True, False, FileNotFound };
yeh i knew how a float was constructed, just needed to know how to extract its bit pattern, thnx now!

Yratelev
Yratelev
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?

[Formerly "capn_midnight". See some of my projects. Find me on twitter tumblr G+ Github.]

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.
- k2"Choose a job you love, and you'll never have to work a day in your life." — Confucius"Logic will get you from A to B. Imagination will get you everywhere." — Albert Einstein"Money is the most egalitarian force in society. It confers power on whoever holds it." — Roger Starr{General Programming Forum FAQ} | {Blog/Journal} | {[email=kkaitan at gmail dot com]e-mail me[/email]} | {excellent webhosting}
Is Longhorn supposed to give a warning about your program if it uses unsafe code?
float f=...;int i = System.BitConverter.ToInt32( System.BitConverter.GetBytes(f) , 0) & 0x007fffff;
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?

This topic is closed to new replies.

Advertisement