C#byte []到List< bool> [英] C# byte[] to List<bool>
本文介绍了C#byte []到List< bool>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从bool []转换为byte []:将bool []转换为byte []
From bool[] to byte[]: Convert bool[] to byte[]
但是我需要将byte []转换为列表,其中列表中的第一项是LSB.
But I need to convert a byte[] to a List where the first item in the list is the LSB.
我尝试了下面的代码,但是当转换为字节并再次转换为bool时,我得到两个完全不同的结果...:
I tried the code below but when converting to bytes and back to bools again I have two totally different results...:
public List<bool> Bits = new List<bool>();
public ToBools(byte[] values)
{
foreach (byte aByte in values)
{
for (int i = 0; i < 7; i++)
{
Bits.Add(aByte.GetBit(i));
}
}
}
public static bool GetBit(this byte b, int index)
{
if (b == 0)
return false;
BitArray ba = b.Byte2BitArray();
return ba[index];
}
推荐答案
您只考虑7位,而不考虑8位.该指令:
You're only considering 7 bits, not 8. This instruction:
for (int i = 0; i < 7; i++)
应该是:
for (int i = 0; i < 8; i++)
无论如何,这是我的实现方式:
Anyway, here's how I would implement it:
byte[] bytes = ...
List<bool> bools = bytes.SelectMany(GetBitsStartingFromLSB).ToList();
...
static IEnumerable<bool> GetBitsStartingFromLSB(byte b)
{
for(int i = 0; i < 8; i++)
{
yield return (b % 2 == 0) ? false : true;
b = (byte)(b >> 1);
}
}
这篇关于C#byte []到List< bool>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文