在c#中将一个位域映射到另一个位域



我有两个位域,一个是8位,一个是4位。

[Flags]
public enum Bits1 {
  A = 1,
  B = 2,
  C = 4,
  D = 8,
  E = 16,
  F = 32,
  G = 64,
  H = 128
}
[Flags]
public enum Bits2 {
  I = 1,
  J = 2,
  K = 4,
  L = 8
}

我需要将Bits1中的位映射到Bits2,像这样:

Bits2 = Map(Bits1)

例如,假设A和C映射到J, B映射到0,D映射到I, ABCD(值为13)经过map函数后,返回IJ(值为3)。

映射应该能够根据需要以编程方式设置和更改。这听起来像是字典可能会做的事情,但我不确定如何设置它。在c#中实现这一点的最好方法是什么?

最好的办法是这样。使用一个数组,其中输入是数组的索引,然后输出数组的值:

public Bits2 Map(Bits1 input)
{
    return _mapping[(int) input];
}

然后您必须定义16个映射如下所示(这只是一个示例):

private static Bits2[] _mapping = new Bits2[16]() {
    Bits2.I | Bits2.J, // this is index 0, so all Bits1 are off
    Bits2.K,           // this is index 1, so all but A are off
    Bits2.I | Bits2.L, // this is index 2, so all but B are off
    Bits2.J | Bits2.K, // this is index 3, so all but A | B are off
    // continue for all 16 combinations of Bits1...
};

这个例子展示了如何对前4个映射进行编码:

none -> I | J
A -> K
B -> I | J
A | B -> J | K

你说

是什么意思?

映射应该能够根据需要以编程方式设置和更改。对我来说,映射似乎是由枚举的定义确定的。在你的问题中,你没有指定如果Bits2中缺少一些标志,代码应该如何表现。实际上,如果不需要检测缺失值,可以这样定义Map函数:

public Bits2 Map(Bits1 input)
{
    return (Bits2)(int)input;
}

当然,如果您需要检测缺失值,那么您可以查看Enum类方法…

最新更新