簡體   English   中英

Byte[] 到浮點數的轉換

[英]Byte[] to float conversion

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

現在我的byte[]值為 82 184 126 63.ie,

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

我想將字節恢復為浮點數。所以,我使用Bitconverter.Tosingle

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

我的疑問是我需要給byte[]值和開始索引。

您能否將解釋的代碼分享為代碼。

value只是保存浮點數的字節數組。
startIndex表示轉換 function 將開始讀取從傳遞的數組中生成浮點數的 4 個字節的偏移量。 在你的情況下,它應該只是 0。

這對我有用。

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

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

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

參數

  • 價值
    字節[]
    一個字節數組。
  • 開始索引
    整數32
    起始值position 以內。

你得到的數組只有 4 個字節長,你需要 4 個字節來創建單個所以 position 應該是 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);
            }
        }
    }
}

Output:

       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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM