2010-03-30 40 views

回答

40

顯而易見的方式;使用需要一個字節數組構造:

BitArray bits = new BitArray(arrayOfBytes); 
+0

那麼預先存在的位數組呢? – Sir 2017-10-04 19:04:43

13

這取決於你所說的「位列」 ...的意思。如果你指的是BitArray類的一個實例,Guffa的回答應該能正常運行。

如果你真的想位的陣列,在bool[]爲實例的形式,你可以做這樣的事情:

byte[] bytes = ... 
bool[] bits = bytes.SelectMany(GetBits).ToArray(); 

... 

IEnumerable<bool> GetBits(byte b) 
{ 
    for(int i = 0; i < 8; i++) 
    { 
     yield return (b & 0x80) != 0; 
     b *= 2; 
    } 
} 
+1

您的答案比上面的答案更合適cos結果包含前導零。 +1 – Nolesh 2013-01-30 05:06:58

2
public static byte[] ToByteArray(this BitArray bits) 
{ 
    int numBytes = bits.Count/8; 
    if (bits.Count % 8 != 0) numBytes++; 
    byte[] bytes = new byte[numBytes]; 
    int byteIndex = 0, bitIndex = 0; 
    for (int i = 0; i < bits.Count; i++) { 
     if (bits[i]) 
      bytes[byteIndex] |= (byte)(1 << (7 - bitIndex)); 
     bitIndex++; 
     if (bitIndex == 8) { 
      bitIndex = 0; 
      byteIndex++; 
     } 
    } 
    return bytes; 
} 
+6

只是好奇..他不想要另一種方式的功能?! – 2013-03-20 19:30:27

0
public static byte[] ToByteArray(bool[] byteArray) 
{ 
    return = byteArray 
       .Select(
        (val1, idx1) => new { Index = idx1/8, Val = (byte)(val1 ? Math.Pow(2, idx1 % 8) : 0) } 
       ) 
       .GroupBy(gb => gb.Index) 
       .Select(val2 => (byte)val2.Sum(s => (byte)s.Val)) 
       .ToArray(); 
} 
0

您可以使用BitArray創建流來自byte陣列的位。這裏的一個例子:

string testMessage = "This is a test message"; 

byte[] messageBytes = Encoding.ASCII.GetBytes(testMessage); 

BitArray messageBits = new BitArray(messageBytes);