Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Convert ushort to float

Tags:

c#

.net

casting

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?

like image 593
gregseth Avatar asked Feb 03 '12 14:02

gregseth


2 Answers

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

like image 75
Mike Dinescu Avatar answered Oct 11 '22 03:10

Mike Dinescu


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.

like image 37
Joachim Isaksson Avatar answered Oct 11 '22 03:10

Joachim Isaksson