2012-02-03 125 views
6

从我正在使用的库中,我收到了一个数组ushortC#:将ushort转换为浮点数

我想将它们转换为float阵列:第一ushort表示第一float和第二ushort的16 MSB LSB是的第一float 16,依此类推。

我试着用类似于以下,但价值被铸造为整数的值,而不是原始位:

ushort[] buffer = { 0xBF80, 0x0000 }; 
float f = (uint)buffer[0] << 16 | buffer[1]; 
// expected result => f == -1   (0xBF800000) 
// effective result => f == 3.21283686E+9 (0x4F3F8000) 

什么建议吗?

回答

9

看看System.BitConverter这个课。

特别是,ToSingle方法采用一系列字节并将它们转换为浮点数。

ushort[] buffer = {0xBF80, 0x0000}; 
byte[] bytes = new byte[4]; 
bytes[0] = (byte)(buffer[1] & 0xFF); 
bytes[1] = (byte)(buffer[1] >> 8); 
bytes[2] = (byte)(buffer[0] & 0xFF); 
bytes[3] = (byte)(buffer[0] >> 8); 
float value = BitConverter.ToSingle(bytes, 0); 

编辑
在这个例子中,我已经扭转了MSB/LSB顺序。现在它是正确的

1

使用C#工会:

[System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit)]  
public struct FloatUShortUnion { 
    [System.Runtime.InteropServices.FieldOffset(0)] 
    float floatValue; 

    [System.Runtime.InteropServices.FieldOffset(0)] 
    ushort short1; 

    [System.Runtime.InteropServices.FieldOffset(16)] 
    ushort short2; 
} 
+0

固定大小数组的C#语法是'fixed ushort buffer [2];',我不确定它是否与'[FieldOffset]'结合使用。 您不能使用普通的C#数组,因为它会将指针转换为数组,而不是数组内容。 – Daniel 2012-02-03 14:56:05

+0

@Daniel谢谢,我最近没有用C#编写程序。 – 2012-02-03 15:42:44

1

我看System.BitConverter类。您可以使用BitConverter.GetBytes将您的ushorts转换为字节数组,然后组合您的字节数组并使用BitConverter将字节数组转换为float。