将字节数组转换为位数组?
我如何将bytearray转换为位数组?
显而易见的方式; 使用带有字节数组的构造函数:
BitArray bits = new BitArray(arrayOfBytes);
这取决于你对“位数组”的意思…如果你的意思是BitArray
类的一个实例,Guffa的答案应该可以正常工作。
如果你真的想要一个位数组,例如bool[]
的forms,你可以这样做:
byte[] bytes = ... bool[] bits = bytes.SelectMany(GetBits).ToArray(); ... IEnumerable GetBits(byte b) { for(int i = 0; i < 8; i++) { yield return (b & 0x80) != 0; b *= 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; }
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(); }
您可以使用BitArray
从byte
数组创建位流。 这是一个例子:
string testMessage = "This is a test message"; byte[] messageBytes = Encoding.ASCII.GetBytes(testMessage); BitArray messageBits = new BitArray(messageBytes);