-3

I have types that have a bitwise value [1,2,4,8,16,32] that are selected from checkboxes, when saving to the database i combine the selected values and get a value of 42 for instance. How can i calculate which values were selected from the combined value, on an edit screen i want to recheck the values that were selected.

  • You can check the [Flags](https://learn.microsoft.com/en-us/dotnet/api/system.flagsattribute?view=netframework-4.7.2) attribute used on `Enums`. You can cast it to an int when saving. – Jeroen van Langen Nov 15 '18 at 08:57
  • 1
    You have the bit values. Use masking (bitwise AND) to find out if a bit is set. For example `value & 16` will be non-zero if the bit with value `16` is set. – Some programmer dude Nov 15 '18 at 08:57
  • `Enumerable.Range(0, 31).Select(i => 1 << i).Where(i => (42 & i) != 0)` => 2, 8, 32. Hope you don't have more than 32 checkboxes, and mind the negative values. (I'm not a fan of this way of storing things.) – Jeroen Mostert Nov 15 '18 at 09:07

2 Answers2

1

To check whether e.g. 8 is contained in your combined value, you can use the bitwise and operator like this:

int combinedValue = 42;
int bitwiseValue = 8;
bool isBitwiseValueChecked = (combinedValue & bitwiseValue) == bitwiseValue;
Stefan Illner
  • 179
  • 1
  • 5
  • 13
0

Use an enum to model the flags:

public static void Main()
{
    Console.WriteLine((MyFlags)1); // Foo
    Console.WriteLine((MyFlags)7); // Foo, Bar, Baz

    Console.WriteLine((int)(MyFlags.Foo | MyFlags.Bar)); // 3
}

[Flags]
enum MyFlags 
{
    Foo = 1,
    Bar = 2,
    Baz = 4
}

Then, to list all members, see List all bit names from a flag Enum

Bas
  • 26,772
  • 8
  • 53
  • 86