问题描述
我们有两个布尔变量,我想像这样:
b1 b2 bin int
true,true = 11 (3)
false,true = 01 (2)
true,false = 10 (1)
false,false = 00 (0)
解决方法
BitVector32
可以做到这一点。
using System.Collections.Specialized;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
var b1 = false;
var b2 = true;
var bitvector = new BitVector32();
bitvector[1] = b1;
bitvector[2] = b2;
var intValue = bitvector.Data;
}
}
}
但是请记住,索引带有位掩码,因此索引需要以2的幂次上升。1,2,4,8,16
等。
可以由1 << n
生成掩码。 n
是您要访问的位(索引为0)。
BitVector32
还提供了一种CreateMask
方法来生成它们。