简体   繁体   中英

C#: Convert ushort to float

From a library I'm working with I recieve an array of ushort .

I want to convert them in an array of float : The first ushort represents the 16 MSB of the first float and the second ushort is the 16 LSB of the first float , and so on.

I tried with something like the following, but the value is cast as the value of the integer, not the raw bits:

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

Any suggestion?

Have a look at the System.BitConverter class.

In particular, the ToSingle method which takes a sequence of bytes and converts them to a float.

 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 );

EDIT
In the example, I had reversed the MSB/LSB order.. Now it is correct

You should use the BitConverter class for that.

Convert the two ushorts to byte arrays with BitConverter.GetBytes(UInt16) , concatenate the two arrays and use BitConverter.ToSingle(byte[] value,int startIndex) to convert the 4 bytes in the resulting array to a float.

Use a C# union:

[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;
}

I'd look at the System.BitConverter class. You can use BitConverter.GetBytes to turn your ushorts into byte arrays, then combine your byte arrays and use BitConverter to turn the byte array into a float.

You will need to use System.BitConverter , and convert the shorts to bytes.

http://msdn.microsoft.com/en-us/library/system.bitconverter.tosingle.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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