I need to convert float to int (single precision, 32 bits) like:
'float: 2 (hex: 40000000) to int: 1073741824'. Any idea how to implement that?
I was looking for it in msdn help but with no result.
-
[link] babbage.cs.qc.edu/IEEE-754/Decimal.htmlsantBart– santBart2011-08-24 10:08:39 +00:00Commented Aug 24, 2011 at 10:08
-
In effect, you want a bit-wise copy? Like C++'s reinterpret_cast?Skizz– Skizz2011-08-24 10:09:04 +00:00Commented Aug 24, 2011 at 10:09
-
Have a look here stackoverflow.com/questions/2578348/…castleofbones– castleofbones2011-08-24 10:15:07 +00:00Commented Aug 24, 2011 at 10:15
-
I'm not sure convert is the right verb.Jodrell– Jodrell2011-08-24 10:21:58 +00:00Commented Aug 24, 2011 at 10:21
-
@castleofbones: that link is to conversions that preserve the represented number. The OP is after a conversion that preserves the binary representation.Paul Ruane– Paul Ruane2011-08-24 10:51:11 +00:00Commented Aug 24, 2011 at 10:51
Add a comment
|
4 Answers
BitConverter.DoubleToInt64Bits, as per the accepted answer of this question.
If the above solution is no good for you (due to it acting upon double/Double rather than float/Single) then see David Heffernan's answer.
1 Comment
David Heffernan
question is about 4 byte float and int
David THANKS, that was a short answer of my long search of analogue for Java method: Float.floatToIntBits. Here is the entire code:
static void Main()
{
float tempVar = -27.25f;
int intBits = BitConverter.ToInt32(BitConverter.GetBytes(tempVar), 0);
string input = Convert.ToString(intBits, 2);
input = input.PadLeft(32, '0');
string sign = input.Substring(0, 1);
string exponent = input.Substring(1, 8);
string mantissa = input.Substring(9, 23);
Console.WriteLine();
Console.WriteLine("Sign = {0}", sign);
Console.WriteLine("Exponent = {0}", exponent);
Console.WriteLine("Mantissa = {0}", mantissa);
}
Comments
If your aiming for versions less than .Net 4 where BitConverter isn't available, or you want to convert floats to 32 bit ints, use a memory stream:
using System;
using System.IO;
namespace Stream
{
class Program
{
static void Main (string [] args)
{
float
f = 1;
int
i;
MemoryStream
s = new MemoryStream ();
BinaryWriter
w = new BinaryWriter (s);
w.Write (f);
s.Position = 0;
BinaryReader
r = new BinaryReader (s);
i = r.ReadInt32 ();
s.Close ();
Console.WriteLine ("Float " + f + " = int " + i);
}
}
}
It is a bit long winded though.