04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 3: Language Basics<br />

As an example, to AND the numbers 25 and 3 together, the code looks like this:<br />

var result = 25 & 3;<br />

alert(result); //1<br />

The result of a bitwise AND between 25 and 3 is 1. Why is that? Take a look:<br />

25 = 0000 0000 0000 0000 0000 0000 0001 1001<br />

3 = 0000 0000 0000 0000 0000 0000 0000 0011<br />

---------------------------------------------<br />

AND = 0000 0000 0000 0000 0000 0000 0000 0001<br />

As you can see, only one bit (bit 0) contains a 1 in both 25 and 3. Because of this, every other bit of the<br />

resulting number is set to 0, making the result equal to 1.<br />

Bitwise OR<br />

The bitwise OR operator is represented by a single pipe character ( | ) and also works on two numbers.<br />

Bitwise OR follows the rules in this truth table:<br />

Bit from First Number Bit from Second Number Result<br />

1 1 1<br />

1 0 1<br />

0 1 1<br />

0 0 0<br />

A bitwise OR operation returns 1 if at least one bit is 1. It returns 0 only if both bits are 0.<br />

Using the same example as for bitwise AND, if you want to OR the numbers 25 and 3 together, the code<br />

looks like this:<br />

var result = 25 | 3;<br />

alert(result); //27<br />

The result of a bitwise OR between 25 and 3 is 27:<br />

25 = 0000 0000 0000 0000 0000 0000 0001 1001<br />

3 = 0000 0000 0000 0000 0000 0000 0000 0011<br />

---------------------------------------------<br />

OR = 0000 0000 0000 0000 0000 0000 0001 1011<br />

In each number, four bits are set to 1, so these are passed through to the result. The binary code 11011 is<br />

equal to 27.<br />

48

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!