如何将布尔列表转换为int?

问题描述 投票:0回答:3

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

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。

c# list int boolean
3个回答
5
投票

你不能,至少不能直接这样做。

可以但是使用

BitArray
类(MSDN)将您的
bool
集合转换为位,然后从中获取一个数字:

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

请注意,此技术也适用于大于 8 位的数字,但您需要使用

BitConverter
(MSDN) 从字节数组中获取值(而不是仅返回第一个值)


0
投票

您可以使用聚合函数来计算等效的 int 值。

var boolList = new List<bool> { true, false, false, false, false, true, false, false };

int integerVal = boolList.Aggregate(0, (sum,val) => (sum * 2) + (val ? 1 : 0));

这里,integerVal为132,相当于二进制值10000100。


0
投票

在控制台应用程序中检查这一点。 首先,在将所需值输入列表后,必须反转列表,然后创建一个字符串值,然后使用循环将值转换为 0 和 1,最后从二进制转换为十六进制.

using System.Data.SqlTypes;

List<bool> boolList = new();

boolList.Add(true);
boolList.Add(true);
boolList.Add(false);
boolList.Add(false);
boolList.Add(false);
boolList.Add(false);
boolList.Add(false);
boolList.Add(false);

boolList.Reverse();

string s = string.Empty;

boolList.ForEach(item =>
{
    s += item ? "1" : "0";
});


Console.WriteLine(Convert.ToInt32(s, 2).ToString("X"));
Console.ReadLine();
© www.soinside.com 2019 - 2024. All rights reserved.