5

I am writing a couple of functions that encode and decode a list of options into a Long so they can easily be passed around the application, you know this kind of thing:

1 - Apple
2 - Orange
4 - Banana
8 - Plum
etc.

In this case the number 11 would represent Apple, Orange & Plum.

I've got it working but I see this used all the time so assume there is a common name for the technique, and no doubt all sorts of best practice and clever algorithms that are at the moment just out of my reach.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Lunatik
  • 3,838
  • 6
  • 37
  • 52

4 Answers4

12

Bit Flags. It's a technique used as part of Bitmasking.

0001 - Apple
0010 - Oranage
0100 - Banana
1000 - Plum

Each 1 is the flagged bit.

Now you can easily perform bitwise operations using those number:

if((11 & Apple) == Apple) // The Apple Flag is set
{
    // Do Something
}
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
3

Bit field: http://en.wikipedia.org/wiki/Bit_field

ckarras
  • 4,946
  • 2
  • 33
  • 37
2

Bitflags

         

H H
  • 263,252
  • 30
  • 330
  • 514
1

going by the help for the c# Flags attribute i'm going to go with a bit field or set of flags

sort of related, in hardware there is also one-hot encoding though this implies you don't get combinations of flags set

jk.
  • 13,817
  • 5
  • 37
  • 50