c# - C# 中的 Bool to bit
问题描述
我们有两个布尔变量,我想是这样的:
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
一种生成它们的方法。
推荐阅读
- javascript - Regex to replace special characters with space from English and Arabic language string using javascript
- css - Angular - 使用 regex 和 css 使用 ngIf 和 ngFor 有条件地格式化标签
- pandas - pandas dataframe multiplication with missing values
- c# - wpf, c# set Margin.Left of FrameWorkElement using Reflection
- wpf - 在以编程方式定义的 WPF GridViewColumnHeader 上定义 Click 事件
- python - How to change text spacing for text in a Tkinter Label?
- sql-server - 子查询返回超过 1 个值。当子查询跟随 = 或子查询用作表达式时,这是不允许的
- swift - 如何访问 SpriteKit 场景编辑器参考节点上自定义类中包含的 Swift 中的变量?
- bitbucket - Bitbucket 迁移主目录并无法启动
- javascript - 数字零在javascript中作为“”工作吗?