C#如何将float转换为int

问题描述:

我需要将float转换为int(单精度,32位),例如:
'float:2(hex:40000000)to int:1073741824'.知道如何实现吗?
我在msdn帮助中寻找它,但是没有结果.

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.

如果您的目标版本低于.Net 4,而BitConverter不可用,或者要将浮点数转换为32位整数,请使用内存流:

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);
    }
  }
}

虽然缠绕有点长.