我该如何将字节阵列转换为位阵列?将字节数组转换为位数组?
24
A
回答
40
显而易见的方式;使用需要一个字节数组构造:
BitArray bits = new BitArray(arrayOfBytes);
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);
相关问题
- 1. 将位图转换为字节数组
- 2. 将位图数组转换为字节数组
- 3. 将字节数组转换为位数组问题
- 4. 将字符串数组(字节值)转换为字节数组
- 5. 将byte []数组转换为字节数
- 6. 将Java字节数组转换为Python字节数组
- 7. 将PNG压缩字节数组转换为BMP字节数组
- 8. 将三维字节数组转换为单字节数组
- 9. 如何将Java字节数组转换为Scala字节数组?
- 10. 将字节数组转换为uint64_t?
- 11. 将C#字节数组转换为VB.NET
- 12. 将对象转换为字节数组
- 13. 将字节数组转换为pdf
- 14. 将字节数组转换为int
- 15. 将字节数组转换为PNG/JPG
- 16. 将C#字节数组转换为C++
- 17. 将字节数组转换为.wav java
- 18. 将字节数组转换为publickey ECDSA
- 19. 将字节数组转换为true/false
- 20. 将表转换为字节数组
- 21. 将字节数组转换为声音
- 22. 将int16转换为字节数组
- 23. 将BitmapImage转换为字节数组
- 24. 将证书转换为字节数组
- 25. VB.Net将字节数组转换为SQLBinary
- 26. PHP将字节数组转换为int
- 27. 将int转换为字节数组BufferOverflowException
- 28. 将图像转换为字节数组?
- 29. 将字节数组转换为图像
- 30. 将字节数组转换为float32
那么预先存在的位数组呢? – Sir 2017-10-04 19:04:43