2010-03-30 39 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);