C#如何将浮点数转换为整数。

5

我需要将浮点数转换为整数(单精度,32位),例如:
'浮点数:2(十六进制:40000000)转换为整数:1073741824'。你有什么实现方法吗?
我在msdn帮助中搜索了一下,但没有结果。


[链接] http://babbage.cs.qc.edu/IEEE-754/Decimal.html - santBart
实际上,您想要按位复制吗?就像C++的reinterpret_cast一样? - Skizz
请看这里:https://dev59.com/wHE85IYBdhLWcg3w2Hbs - castleofbones
我不确定“convert”是正确的动词。 - Jodrell
@castleofbones:该链接是关于保留表示数字的转换。OP需要的是保留二进制表示的转换。 - Paul Ruane
4个回答

10
float f = ...;
int i = BitConverter.ToInt32(BitConverter.GetBytes(f), 0);

2

1
问题涉及4字节浮点数和整数。 - David Heffernan

1

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

-1
如果你的目标是低于 .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);
    }
  }
}

虽然略显冗长。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接