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.
Asked
Active
Viewed 6,973 times
5
-
[link] http://babbage.cs.qc.edu/IEEE-754/Decimal.html – santBart Aug 24 '11 at 10:08
-
In effect, you want a bit-wise copy? Like C++'s reinterpret_cast? – Skizz Aug 24 '11 at 10:09
-
Have a look here http://stackoverflow.com/questions/2578348/c-converting-a-float-to-an-int-and-changing-the-int-depending-on-the-remain – castleofbones Aug 24 '11 at 10:15
-
I'm not sure convert is the right verb. – Jodrell Aug 24 '11 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 Aug 24 '11 at 10:51
4 Answers
10
float f = ...;
int i = BitConverter.ToInt32(BitConverter.GetBytes(f), 0);

David Heffernan
- 601,492
- 42
- 1,072
- 1,490
2
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.

Community
- 1
- 1

Paul Ruane
- 37,459
- 12
- 63
- 82
1
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);
}

Deko
- 439
- 4
- 4
-1
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.

Skizz
- 69,698
- 10
- 71
- 108