我有一个布尔数组:
bool[] b6=new bool[] {true, true, true, true, true, false, true, true,
true, false, true, false, true, true, false, false };
我如何将其转换为字节数组,使得:
- byte[0]=0xFB
- byte[1]=AC
- 等等
我有一个布尔数组:
bool[] b6=new bool[] {true, true, true, true, true, false, true, true,
true, false, true, false, true, true, false, false };
我认为你想要的是这样的:
static byte[] ToByteArray(bool[] input)
{
if (input.Length % 8 != 0)
{
throw new ArgumentException("input");
}
byte[] ret = new byte[input.Length / 8];
for (int i = 0; i < input.Length; i += 8)
{
int value = 0;
for (int j = 0; j < 8; j++)
{
if (input[i + j])
{
value += 1 << (7 - j);
}
}
ret[i / 8] = (byte) value;
}
return ret;
}
编辑:在明确要求之前的原始回答:
您并没有说明想要实现什么样的转换。例如,这个会起作用:
byte[] converted = Array.ConvertAll(b6, value => value ? (byte) 1 : (byte) 0);
或者类似地(但效率稍低)使用LINQ:
byte[] converted = b6.Select(value => value ? (byte) 1 : (byte) 0).ToArray();
Array.ConvertAll
这个方法。以为在使用 ConvertAll
之前必须调用 ToList()
,所以对你的分享表示感谢 :) - Øyvind Bråthenvalue += 1 << j;
这一行更改为使用不同的位移量进行移位即可...) - Jon SkeetBitArray
类:byte[] data = new byte[2];
new BitArray(b6).CopyTo(data, 0);
数组data
现在包含两个值0xDF和0x35。
如果你想要结果为0xFB和0xAC,你需要先反转数组中的布尔值:
Array.Reverse(b6, 0, 8);
Array.Reverse(b6, 8, 8);
bytes = (from bit in b6 select bit ? (byte)1 : (byte)0).ToArray()
var byteArray =
b6
.Select(b => (byte)(b ? 1 : 0))
.ToArray();
byte[] byteArray = Array.ConvertAll(b6, b => b ? (byte)1 : (byte)0);
true
应该转换成什么?而false
呢? - Emond