Convert raw byte data to float []

I have this code to convert byte[]to float[].

public float[] ConvertByteToFloat(byte[] array)
{
    float[] floatArr = new float[array.Length / sizeof(float)];
    int index = 0;
    for (int i = 0; i < floatArr.Length; i++)
    {
        floatArr[i] = BitConverter.ToSingle(array, index);
        index += sizeof(float);
    }
    return floatArr;
}

The problem is that I usually get the result NaN! Why should it be? I checked if the data is in byte[]and the data seems beautiful. If this helps, example values:

new byte[] {
    231,
    255,
    235,
    255,
}

But this returns NaN(Not a Number) after converting to float. What could be the problem? Are there other ways to convert byte[]to float[]? I am sure that the values ​​read into the buffer are correct, since I compared them with my other program (which performs amplification for a WAV file).

+3
source share
5 answers

, BitConverter.IsLittleEndian, , :

public static float[] ConvertByteToFloat(byte[] array) {
  float[] floatArr = new float[array.Length / 4];
  for (int i = 0; i < floatArr.Length; i++) {
    if (BitConverter.IsLittleEndian) {
      Array.Reverse(array, i * 4, 4);
    }
    floatArr[i] = BitConverter.ToSingle(array, i * 4);
  }
  return floatArr;
}
+4

, 255 NaN (. Wikipedia ), NaN. 255 - ...

+2

( ), ( , "", )

public static unsafe int ToInt32(byte[] value, int startIndex)
{
    fixed (byte* numRef = &value[startIndex])
    {
        var num = (uint)((numRef[0] << 0x18) | (numRef[1] << 0x10) | (numRef[2] << 0x8) | numRef[3]);
        return (int)num;
    }
}

public static unsafe float ToSingle(byte[] value, int startIndex)
{
    int val = ToInt32(value, startIndex);
    return *(float*)&val;
}
+1

, [] , Int8, Int16 s. float ( NaN, -2.41E + 24 -1 1. , 8 16 .

, , - , . , , , ... .

, , . .

, Int8/16. float -1 1.

, BitConverter. , , - -. , . .

( ):

float Int8ToFloat(Int8 i)
{
  return ((i-Int8.MinValue)*(1f/0xFF))-0.5f;
}

float Int16ToFloat(Int16 i)
{
  return ((i-Int16.MinValue)*(1f/0xFFFF))-0.5f;
}
+1

, float. , , . , ? ?

In the case where each byte must be converted to a float from 0 to 255:

public float[] ConvertByteToFloat(byte[] array)
{
    return array.Select(b => (float)b).ToArray();
}

If the byte array contains a binary representation of the floats, there are several representations, and if the representation stored in your file does not match the C # language standard floating point representation ( IEEE 754 ) there will be strange things like this happening.

0
source

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


All Articles