Byte[] 到 float 的转换

Byte[] to float conversion

Float b = 0.995;
Byte[] a = Bitconverter.GetBytes(b);

现在我的 byte[] 值为 82 184 126 63 .i.e.,

a[0] = 82, a[1] =184, a[2] = 126, and a[3] = 63.

我想将上面的字节还原为float.So,我使用了Bitconverter.Tosingle

Float b = Bitconverter.Tosingle(byte[] value,start index)

我的疑问是我需要给byte[]值和起始索引。

能否请您将解释作为代码分享。

value 只是保存浮点数的字节数组。
startIndex 表示转换函数将开始从传递的数组中读取构成浮点数的 4 个字节的偏移量。在你的情况下它应该只是 0.

这对我有用。

float val = (float)0.995;
Byte[] arr = BitConverter.GetBytes(val);

float myFloat = BitConverter.ToSingle(arr, 0);

BitConverter.ToSingle(byte[] value, int startIndex)

Parameters

  • value
    Byte[]
    An array of bytes.
  • startIndex
    Int32
    The starting position within value.

你得到的数组只有 4 个字节长,你需要 4 个字节来创建单个所以位置应该是 0 - 所有其他的给你例外:

using System;

public class Program
{
    public static void Main()
    {
        var b = 0.995f;
        Byte[] a = BitConverter.GetBytes(b);
        Console.WriteLine("{0,16:f7}{1,20}\n", b, BitConverter.ToString(a));
        for (var pos = 0; pos < a.Length; pos++)
        {
            try {
                var c = BitConverter.ToSingle(a, pos);
                Console.WriteLine("{0} is valid:",pos);
                Console.WriteLine("{0}\n",c);
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} is invalid: {1}",pos,e);
            }
        }
    }
}

输出:

       0.9950000         52-B8-7E-3F

0 is valid:
0.995

1 is invalid: System.ArgumentException: Destination array is not long enough to copy all the 
              items in the collection. Check array index and length.
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.BitConverter.ToSingle(Byte[] value, Int32 startIndex)
   at Program.Main() in d:\Windows\Temp\cowicrki.0.cs:line 13
2 is invalid: System.ArgumentException: Destination array is not long enough to copy all the 
              items in the collection. Check array index and length.
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.BitConverter.ToSingle(Byte[] value, Int32 startIndex)
   at Program.Main() in d:\Windows\Temp\cowicrki.0.cs:line 13
3 is invalid: System.ArgumentException: Destination array is not long enough to copy all the 
              items in the collection. Check array index and length.
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.BitConverter.ToSingle(Byte[] value, Int32 startIndex)
   at Program.Main() in d:\Windows\Temp\cowicrki.0.cs:line 13