【问题标题】:Bool to bit in the C# [closed]在 C# 中使用 Bool to bit [关闭]
【发布时间】:2020-09-13 07:40:47
【问题描述】:

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

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

【问题讨论】:

标签: c# binary boolean boolean-operations


【解决方案1】:

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 方法来生成它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多