问题描述
如何将布尔值列表转换为等于解释为字节的布尔值的整数?
How do I convert a boolean list to an integer equal to the Booleans interpreted as a byte?
即
public List<Boolean> MyList = new List<Boolean>();
MyList.Add(true);
MyList.Add(true);
MyList.Add(false);
MyList.Add(false);
MyList.Add(false);
MyList.Add(false);
MyList.Add(false);
MyList.Add(false);
这将返回3.
推荐答案
您不能,至少不能直接这样做.
You can't, at least not directly.
您可以使用BitArray
类( MSDN ),将您的bool
集合转换为位,然后从中获取一个数字:
You can however use the BitArray
class (MSDN) to transform your bool
collection to bits, and then get a number from that:
BitArray bitField = new BitArray(MyList.ToArray()); //BitArray takes a bool[]
byte[] bytes = new byte[1];
bitField.CopyTo(bytes, 0);
return bytes[0];
从以下位置将BitArray转换为值: https://stackoverflow.com/a/560131/1783619
BitArray to value conversion from: https://stackoverflow.com/a/560131/1783619
请注意,此技术也适用于大于8位的数字,但是您需要使用BitConverter
( MSDN )以从字节数组中获取值(而不是仅返回第一个)
Note that this technique works for numbers larger than 8-bit as well, but you would need to use BitConverter
(MSDN) to get the values back from the byte array (instead of just returning the first one)
这篇关于如何将布尔值列表转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!