2016-08-27 38 views
0

我有兩個位域,一個是8位,另一個是4位。將位域映射到C#中的另一個位域

[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映射到什麼,d映射到我在映射中,ABCD(值爲13)在通過map函數後返回IJ(值爲3)。

地圖應該能夠根據需要進行編程設置和更改。這聽起來像一個字典可能能做的事情,但我不知道如何設置它。在C#中完成此操作的最佳方法是什麼?

+0

也許我可以根據我想要使用的映射生成一個位掩碼,然後將位掩碼應用到第一個位域? – GameKyuubi

回答

1

最好的辦法是這樣。使用一個陣列,其中所述輸入是索引到陣列和你輸出數組的值:

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 
0

你是什麼

意思

地圖應該能夠根據需要進行編程設置和更改。 對我來說,映射似乎是由枚舉的定義所固定的。在你的問題中,如果Bits2中缺少某些標誌,則不會指定代碼的行爲方式。事實上,Map函數可以這樣定義,如果你不需要檢測缺失值:

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

當然,如果你需要檢測缺失值,那麼你可以看看Enum類的方法。 ..

+0

我需要能夠添加個別映射,並清除,獲取和設置整個映射,這就是爲什麼我正在考慮字典。 – GameKyuubi

+0

如果您沒有名稱或值的直接映射,那麼您需要編寫一些真實的代碼... – Phil1970