简体   繁体   English

c#如何将float转换为int

[英]c# how to convert float to int

I need to convert float to int (single precision, 32 bits) like: 我需要将float转换为int(单精度,32位),如:
'float: 2 (hex: 40000000) to int: 1073741824'. '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. 我在msdn帮助中寻找它但没有结果。

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

BitConverter.DoubleToInt64Bits , as per the accepted answer of this question . BitConverter.DoubleToInt64Bits ,根据这个问题的接受答案。

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 . 如果上述解决方案对你没有好处(由于它采取double / Double而不是float / Single ),那么请参阅David Heffernan的回答

David THANKS, that was a short answer of my long search of analogue for Java method: Float.floatToIntBits. David THANKS,这是我长期搜索Java方法模拟的简短回答: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);
}

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

It is a bit long winded though. 虽然这有点长。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM