“Smart Options” or “Binary Operators” Hey folks,

you have probably seen a method call like this:

foo('bar', ESCAPE<em>QUOTES | ESCAPE</em>DOUBLE | ESCAPE_LONG);

As I designed my Slideme jQuery plugin I wanted to use such a method to enable swiping directions.

With a little help from a friend of mine I finally got a solution. You cannot use random numbers. They have to be a presentable as a exponent of 2 ( 2^0, 2^1, 2^2, 2^3, 2^4, …) Which is the same as 1, 2, 4, 8, 16, …

The number 1 converted into binary is 00000001. In most programming languages there is a operator like <<. It will “shift” the bit. (so it’s called bitshift-operator) If you call 1 << 1 it converts 00000001 into 00000010( i << n ; i = variable to shift; n = numbers of bits to move left )

We will use the variables

A = 1 << 0 which is  which is 1 B = 1 << 2 which is  which is 4 C = 1 << 4 which is  which is 16

for this example.

You will see that the bit moves to the left. Now we can put them together. For this we use the |-operator. It’s called the bit-OR operator. If you OR two bits together it works like this:

1 | 0
1 | 1 | 1
0 | 1 | 0

This means: If A is 1 and/or B is 1 then the solution is 1.

so now we can calculate: A | B:

00000001
| 00000100

= 00000101

A | B | C:

00000001
| 00000100
| 00010000

= 00010101

Thats the calculation. Now we want to know if the C-flag is set. For this scope we use the &-operator. The &-operator or AND-operator works like this:

1 | 0
1 | 1 | 0
0 | 0 | 0

This means: Only if A and B are 1 than the solution will be 1

00000101
& 00010000

= 00000000  --> this converted into a boolean is false --> the C-flag is not set!

another example

00000111
& 00010000

= 00010000  --> this converted into a boolean is true --> the C-flag is set!

Here is an JavaScript example:

var LEFT = 1 << 0; var RIGHT = 1 << 1; var UP = 1 << 2; var DOWN = 1 << 3; var HORIZONTAL = LEFT | RIGHT; function is_horizontal( test ) { return !!( HORIZONTAL & test ); } alert( is_horizontal(LEFT) + ' :: '+ is_horizontal(DOWN) ); // --> true :: false

If you wonder what the !! before the &-statement means… It just converts a variable into a boolean with this in mind …