如何将int转换为bool数组?

Jak*_*les 16 c#

如何将int转换为bool数组(表示整数中的位)?例如:

4 = { true, false, false }
7 = { true, true, true }
255 = { true, true, true, true, true, true, true, true }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 14

一个int应很好地映射到BitVector32(或BitArray)

int i = 4;
var bv = new BitVector32(i);
bool x = bv[0], y = bv[1], z = bv[2]; // example access via indexer
Run Code Online (Sandbox Code Playgroud)

但是,我个人只是使​​用轮班(>>等)并将其作为一个int.该bool[]会是多少更大

  • BitVector ......你永远不会知道框架内的所有类...谢谢:) (2认同)

GvS*_*GvS 8

您可以使用BitArray.

var bools = new BitArray(new int[] { yourInt }).Cast<bool>().ToArray();
Run Code Online (Sandbox Code Playgroud)


dec*_*one 7

Int32 number = 10;

var array = Convert.ToString(number, 2).Select(s => s.Equals('1')).ToArray();
Run Code Online (Sandbox Code Playgroud)

- 编辑 -

使用扩展方法:

public static class Int32Extensions
{
    public static Boolean[] ToBooleanArray(this Int32 i)
    {
        return Convert.ToString(i, 2 /*for binary*/).Select(s => s.Equals('1')).ToArray();
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

var boolArray = number.ToBooleanArray();
Run Code Online (Sandbox Code Playgroud)

  • 需要注意的是,这将截断所有前导零.我不得不填充我的bool阵列的前面,直到它的长度为32. (4认同)