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

现在我的byte[]值是 82 184 126 63 。即,

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

我想恢复到字节以上浮动。所以,我用Bitconverter.Tosingle

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

我的疑问是我需要赋予byte[]价值并开始索引。

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

4

3 回答 3

0

这对我有用。

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

float myFloat = BitConverter.ToSingle(arr, 0);
于 2020-06-19T07:00:56.713 回答
0

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
于 2020-06-19T07:02:55.060 回答
0

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

于 2020-06-19T06:52:07.493 回答