将原始字节数据转换为float [],值必须介于-1和1之间

时间:2017-05-22 10:58:54

标签: c# arrays byte bitconverter

如果我正确行事,我不会这样做,但我正在使用此方法将字节数组转换为float数组,如link所示:

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

输入数组是一个包含wave原始数据(没有标题)的数组

问题是我得到(转换后)的值如:

  

-9.66012E + 24,1963.15576,-5.11384777E-36,-1.19718621E-07

如何将此数组转换为float数组,其值应介于-1.0和1.0之间

编辑:

我的输入数组如下所示:

byte[] {
    232,
    255,
    235,
    255,
    232,
    255,
    235,
    255,
    232,
    255,
    235,
    255,
    232,
    255,
    235,
    255,
...
}

1 个答案:

答案 0 :(得分:3)

您可以查看the implementation of WriteSample()

    public void WriteSample(float sample)
    {
        if (WaveFormat.BitsPerSample == 16)
        {
            writer.Write((Int16)(Int16.MaxValue * sample));
            dataChunkSize += 2;
        }
        ...

请注意它如何通过将float乘以Int16.MaxValueInt16转换为16位有符号整数。那是因为内部数据格式是-Int16.MaxValue和+ Int16.MaxValue之间的16位整数。

这意味着您使用的值为short(又名Int16.MaxValue),您需要将它们除以byte[] bytes = { 232, 255, 235, 255, 232, 255, 235, 255, 232, 255, 235, 255, 232, 255, 235, 255 }; for (int i = 0; i < bytes.Length - 4; i += 4) { float f = BitConverter.ToInt16(bytes, i) / (float)Int16.MaxValue; Console.WriteLine(f); } 将其转换回浮点数。

例如,给出您的样本输入:

export class MyClass {
 name: string 
 op: string 
 field_id: string
 comparsion_values: {
  values: [
    string
  ],
  list_ids: [number] 
  field_ids: [
    string 
  ],
  velocities: [
    string 
  ],
  prices: [
    {
     amount: 0 
     currency: string 
    }
  ]
 }
}