簡體   English   中英

如何在C#中將任意大小的字節數組轉換為ulong?

[英]How to convert a byte array of any size to ulong in C#?

考慮具有不同長度的各種字節 arrays,例如:

byte[] a = new byte[]{0x6};
byte[] b = new byte[]{0x6, 0x33, 0x22};
byte[] c = new byte[]{0x6, 0x33, 0x22, 0x14, 0x47};

如何將這些字節 arrays 基本上任何大小(除了大於 8 個字節)轉換為ulong

我知道 C# 中的BitConverter class,但是您必須始終提供確切的字節數...

您可以使用 for 循環和位移輕松地做到這一點:

public static ulong BytesToUInt64(byte[] bytes)
{
    if (bytes == null)
        throw new ArgumentNullException(nameof(bytes));
    if (bytes.Length > 8)
        throw new ArgumentException("Must be 8 elements or fewer", nameof(bytes));

    ulong result = 0;
    for (int i = 0; i < bytes.Length; i++)
    {
        result |= (ulong)bytes[i] << (i * 8);
    }   
    
    return result;
}

在 SharpLab 上查看

我們取字節數組中的第一個元素,並使用按位或將其組合成result 我們取第二個元素,將其向左移動 8 位(因此它正好位於第一個元素的頂部),然后將其移入。對於剩余的字節,依此類推。

請注意,這會將索引 0 處的字節放在最不重要的 position 中。 如果需要,您可以擺弄bytes索引和左移來更改它。


您也可以通過用 0 填充字節數組來解決此問題。 盡管從表面上看效率較低,但它可能仍然比上面的循環和位移更便宜(更清晰)。 有關詳細信息, 請參閱此問題

您可以考慮兩種情況:完整和不完整的data數組。 如果您想擁有BitConverter改進版:

public static ulong MyToUInt64(byte[] data) {
  if (null == data)
    throw new ArgumentNullException(nameof(data)); // or return 0

  if (data.Length >= sizeof(ulong)) // we have enough bytes (at least 8)
    return BitConverter.ToUInt64(data, 0);

  // padded version (8 bytes) of data array
  byte[] complete = new byte[sizeof(ulong)];

  for (int i = 0; i < data.Length; ++i) 
    if (BitConverter.IsLittleEndian) // we have two ways of padding
      complete[i] = data[i];
    else 
      complete[complete.Length - i - 1] = data[data.Length - i - 1];

  return BitConverter.ToUInt64(complete);
}

暫無
暫無

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

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