【问题标题】:c# how to convert float to intc#如何将float转换为int
【发布时间】:2011-11-02 16:09:21
【问题描述】:

我需要将 float 转换为 int(单精度,32 位),例如:
'浮点数:2(十六进制:40000000)到整数:1073741824'。知道如何实现吗?
我在 msdn 帮助中寻找它,但没有结果。

【问题讨论】:

标签: c# floating-point int


【解决方案1】:

BitConverter.DoubleToInt64Bits,根据this question 接受的答案。

如果上述解决方案对您不利(因为它作用于double/Double 而不是float/Single),请参阅David Heffernan's answer

【讨论】:

  • 问题大约是4字节浮点数和整数
【解决方案2】:

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

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

虽然有点啰嗦。

【讨论】:

    【解决方案3】:
    float f = ...;
    int i = BitConverter.ToInt32(BitConverter.GetBytes(f), 0);
    

    【讨论】:

      【解决方案4】:

      David 谢谢,这是我长期搜索 Java 方法的一个简短答案:Float.floatToIntBits。完整代码如下:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-11
        • 2021-10-12
        • 2019-12-04
        • 2011-08-09
        • 2017-09-04
        • 1970-01-01
        • 2016-08-19
        • 2012-05-05
        相关资源
        最近更新 更多