首页 > 解决方案 > C# 中的 Bool to bit

问题描述

我们有两个布尔变量,我想是这样的:

b1      b2       bin  int
true ,  true =   11   (3)
false , true =   01   (2)
true ,  false =  10   (1)
false , false =  00   (0)

标签: c#binarybooleanboolean-operations

解决方案


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 << nn您要访问的位在哪里(索引为 0)。

BitVector32还提供了CreateMask一种生成它们的方法。


推荐阅读