Anonymouss Anonymouss - 9 months ago 48
C# Question

Perform addition on bit-fields in C#

I am working on a Gomoku implementation in C#, and the first challenge of the project is to intelligently represent the state of the board.

In order to achieve this goal, I decided to turn to bit-fields to represent the value of a combination:

public enum CombinationValue : byte
OnePawn = 1,
TwoPawns = 2,
ThreePawn = 4,
FourPawn = 8,
FivePawns = 16

The problem that I stumbled on, is that when I want to increment a combination, I want to unset the previous bit and set a new one, which is basically a binary shift to the left, which is not allowed with enum.
For example, let's say I have a combination of two pawns, and a pawn is put next to it so the value of the enum must become "ThreePawn" instead of "TwoPawns".

So basically, what I want to do is TwoPawns + OnePawn == ThreePawns.

What would be the most efficient way to implement this behavior?

Answer Source

This isn't how flags should be used. Flags are used to designate switches in a single byte, so given the binary 0000 the first bit represents an element being "on", the second a different element, etc.

So element1 is represented by: 1 = 0001, Element2: 2= 0010, Element3: 4 = 0100, etc. So to turn element 1 and element 2 on you use the binary 0011 or 3 (1+2).

FYI; this dates back to the days when computers had limited memory and being able to represent multiple states in a small number of bits was advantagous.

What you want doesn't make sense from a binary point of view, three prawns would be 0011 or switch 1 and 2. This isn't really a "state". which is what switches are for.

If you want to designate the number of prawns and perfrom addition, what's wrong with a good old fashined int?