BitConverter.ToSingle(byte[] value, int startIndex)
参数
- value
Byte[]
一个字节数组。
- startIndex
Int32值
内的起始位置。
你得到的数组只有 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