Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a name for the technique of using base-2 numbers to encode a list of unique options?

Apologies for the rather vague nature of this question, I've never formally been taught programming and Google is rather useless to a self-help guy like me in this case as the key words are pretty ambiguous.

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.

Edit: Thanks to all, I knew the answer would come swiftly :)

like image 713
Lunatik Avatar asked Jun 01 '10 15:06

Lunatik


2 Answers

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
}
like image 54
Justin Niessner Avatar answered Sep 20 '22 18:09

Justin Niessner


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

like image 41
ckarras Avatar answered Sep 20 '22 18:09

ckarras