C #: convert ordering to float

From the library I'm working with, I get an ushort array.

I want to convert them to a float array: the first ushort represents 16 MSB of the first float , and the second ushort is 16 LSB of the first float , and therefore on.

I tried to do something like the following, but the value is passed as an 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?

+6
source share
5 answers

Take a look at the System.BitConverter class.

In particular, the ToSingle method, which takes a sequence of bytes and converts them to 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 this example, I reordered the MSB / LSB. Now this is correct.

+9
source

To do this, you must use the BitConverter class.

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

+2
source

Use C # join:

 [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; } 
+1
source

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

+1
source

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

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

0
source

Source: https://habr.com/ru/post/907575/


All Articles