本文介绍了转换布尔[]为byte []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表<布尔>
我要转换为字节[]
。我该怎么做呢? list.toArray()
创建一个布尔[]
。
I have a List<bool>
which I want to convert to a byte[]
. How do i do this? list.toArray()
creates a bool[]
.
推荐答案
下面是两种方法,这取决于你是否要位打包成字节,或有尽可能多的字节作为原始位:
Here's two approaches, depending on whether you want to pack the bits into bytes, or have as many bytes as original bits:
bool[] bools = { true, false, true, false, false, true, false, true,
true };
// basic - same count
byte[] arr1 = Array.ConvertAll(bools, b => b ? (byte)1 : (byte)0);
// pack (in this case, using the first bool as the lsb - if you want
// the first bool as the msb, reverse things ;-p)
int bytes = bools.Length / 8;
if ((bools.Length % 8) != 0) bytes++;
byte[] arr2 = new byte[bytes];
int bitIndex = 0, byteIndex = 0;
for (int i = 0; i < bools.Length; i++)
{
if (bools[i])
{
arr2[byteIndex] |= (byte)(((byte)1) << bitIndex);
}
bitIndex++;
if (bitIndex == 8)
{
bitIndex = 0;
byteIndex++;
}
}
这篇关于转换布尔[]为byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!