c# how to convert float to int
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.
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.
float f = ...;
int i = BitConverter.ToInt32(BitConverter.GetBytes(f), 0);
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)执行的速度比没有OpenMP快
下一篇: c#如何将float转换为int