Search code examples
c#.netcasting

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?


Solution

  • 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