我需要将浮点数转换为整数(单精度,32位),例如:
'浮点数:2(十六进制:40000000)转换为整数:1073741824'。你有什么实现方法吗?
我在msdn帮助中搜索了一下,但没有结果。
我需要将浮点数转换为整数(单精度,32位),例如:
'浮点数:2(十六进制:40000000)转换为整数:1073741824'。你有什么实现方法吗?
我在msdn帮助中搜索了一下,但没有结果。
float f = ...;
int i = BitConverter.ToInt32(BitConverter.GetBytes(f), 0);
BitConverter.DoubleToInt64Bits,根据这个问题的被接受的答案。
如果上述解决方案不适用于您(因为它作用于double
/Double
而不是float
/Single
),请参见David Heffernan的答案。
谢谢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);
}
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);
}
}
}
虽然略显冗长。