如何将布尔值列表转换为int? [英] How do I convert a boolean list to int?

查看:298
本文介绍了如何将布尔值列表转换为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将布尔值列表转换为等于解释为字节的布尔值的整数?

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类(

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(

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆