4

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.

5
  • [link] babbage.cs.qc.edu/IEEE-754/Decimal.html Commented Aug 24, 2011 at 10:08
  • In effect, you want a bit-wise copy? Like C++'s reinterpret_cast? Commented Aug 24, 2011 at 10:09
  • Have a look here stackoverflow.com/questions/2578348/… Commented Aug 24, 2011 at 10:15
  • I'm not sure convert is the right verb. Commented 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. Commented Aug 24, 2011 at 10:51

4 Answers 4

9
float f = ...;
int i = BitConverter.ToInt32(BitConverter.GetBytes(f), 0);
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

question is about 4 byte float and int
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);
}

Comments

-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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.