簡體   English   中英

以2為基數的字節數組

[英]Base 2 byte array to string

我有一個字節數組(byte [16]),每個單元格中都有一個字節:

0000000000010010 -> [0][0] ..... [1][0][0][1][0].

如何獲得以2為底的邏輯的結果?

我想得到結果: 18 我使用C#。

假設您的字節數組純粹是0 s和1 s),應該能夠使用以下內容(盡管如果是這種情況,則bool[]可能是更好的選擇),並且最高有效位是第0個元素。

private int BytesToInt(byte[] byteArray)
{
    // Start with zero
    int result = 0;
    foreach (var b in byteArray)
    {
        // For each item in the array, first left-shift the result one bit
        result <<= 1;
        // If the byte is non-zero, set the lowest bit in the result
        if (b != 0) result |= 1;
    }
    return result;
}

有點麻煩的事情應該做。 LINQ單線:

public static ushort ToUShort( this byte[] buffer )
{
  const int ushort_bits = sizeof(ushort) * 8 ;
  int bits = ushort_bits - 1 ;
  return (ushort) buffer
                  .Take( ushort_bits ) 
                  .Select( b => b != 0 ? 1 : 0 )
                  .Aggregate(0 , (acc,b) => acc | (b<<(bits--)))
                  ;
}

或同樣簡潔(可能更快):

public static ushort ToUShort( this byte[] buffer )
{
  uint acc = 0 ;
  int bits = sizeof(ushort) * 8 - 1 ;
  int max  = sizeof(ushort) * 8     ;
  for ( int i = 0 ; i < max  ; ++i )
  {
    acc |= (buffer[i]==0?0u:1u)<<(bits--) ;
  }
  return (ushort) acc ;
}

暫無
暫無

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

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