最接近的直接等同於你的C方法將是不安全的代碼要做到這一點,和指針:
private static unsafe void SplitToWords(float f, out ushort s1, out ushort s2)
{
unsafe
{
float* ptr = &f;
UInt16* s2ptr = (UInt16*) ptr;
UInt16* s1ptr = s2ptr + 1;
s1 = *s1ptr;
s2 = *s2ptr;
}
}
這讓你做:
public static void Main()
{
float f = -23984.123f;
ushort s1;
ushort s2;
SplitToWords(f, out s1, out s2);
Console.WriteLine("{0} : {1}/{2}", f, s1, s2);
Console.ReadKey();
}
但是,更常用的管理方式是使用BitConverter。
byte[] fBytes = BitConverter.GetBytes(f);
s1 = BitConverter.ToUInt16(fBytes, 2);
s2 = BitConverter.ToUInt16(fBytes, 0);
你可以看到這些產品在這裏同樣的事情:
public static void Main()
{
float f = -23984.123f;
ushort s1;
ushort s2;
SplitToWords(f, out s1, out s2);
Console.WriteLine("{0} : {1}/{2}", f, s1, s2);
byte[] fBytes = BitConverter.GetBytes(f);
s2 = BitConverter.ToUInt16(fBytes, 0);
s1 = BitConverter.ToUInt16(fBytes, 2);
Console.WriteLine("{0} : {1}/{2}", f, s1, s2);
Console.ReadKey();
}
在C#的更好的新的一天,我們更清楚地知道我們如何轉換;-) – 2010-04-30 18:19:48