5

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.

mskfisher
  • 3,291
  • 4
  • 35
  • 48
santBart
  • 2,466
  • 9
  • 43
  • 66

4 Answers4

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