0

I have two bitfields, one of 8 bits and one of 4 bits.

[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
}

I need to map the bits in Bits1 to Bits2, like this:

Bits2 = Map(Bits1)

For example, supposing that A and C map to J, B maps to nothing, and D maps to I in the mapping, ABCD(value of 13), after going through the map function, returns IJ(value of 3).

The map should be able to be set and changed programmatically as needed. This sounds like something a Dictionary might be able to do, but I'm not sure how to set it up. What would be the best way to accomplish this in C#?

GameKyuubi
  • 681
  • 1
  • 10
  • 25
  • Maybe I could generate a bitmask based on the mapping I want to use, and then apply the bitmask to the first bitfield? – GameKyuubi Aug 27 '16 at 11:49

2 Answers2

1

The best way is this. Use an array where the input is the index into the array and you output the value of the array:

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

You have then to define the 16 mappings as follows (this is just an example):

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...
};

The example shows how to encode the first 4 mappings:

none -> I | J
A -> K
B -> I | J
A | B -> J | K
pid
  • 11,472
  • 6
  • 34
  • 63
0

What do you mean by

The map should be able to be set and changed programmatically as needed. To me, it seems that the mapping is fixed by the definition of the enums. In your question, you don't specify how the code should behave if some flags are missing in the Bits2. In fact, Map function could be defined like this if you don't need to detect missing values:

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

Of course, if you need to detect missing value, then you can look at Enum class methods...

Phil1970
  • 2,605
  • 2
  • 14
  • 15
  • I need to be able to add individual mappings, and clear, get, and set entire mappings on the fly, which is why I was considering a dictionary. – GameKyuubi Aug 28 '16 at 03:03
  • If you don't have a direct mapping of names or values, then you need to write some real code... – Phil1970 Aug 28 '16 at 21:34