﻿ Bitwise OR ﻿

Main Page

# Bitwise OR

var iResult = 25 & 3;
The result of a bitwise AND between 25 and 3 is 1. Why is that? Take a look:
25 = 0000 0000 0000 0000 0000 0000 0001 1001
3 = 0000 0000 0000 0000 0000 0000 0000 0011
---------------------------------------------
AND = 0000 0000 0000 0000 0000 0000 0000 0001
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
resulting number is set to 0, making the result equal to 1.
Bitwise OR
The bitwise OR operator is indicated by the pipe (
|
) and also works directly on the binary form of num-
bers. Essentially, bitwise OR follows these rules when evaluating bits:
Bit from First Number Bit from Second Number
Result
1
1
1
1
0
1
0
1
1
0
0
0
Using the same example as for bitwise AND, if you want to OR the numbers 25 and 3 together, the code
looks like this:
var iResult = 25 | 3;
The result of a bitwise OR between 25 and 3 is 27:
25 = 0000 0000 0000 0000 0000 0000 0001 1001
3 = 0000 0000 0000 0000 0000 0000 0000 0011
---------------------------------------------
OR = 0000 0000 0000 0000 0000 0000 0001 1011
As you can see, four bits contain 1 in either number, so these are passed through to the result. The binary
code 11011 is equal to 27.
Bitwise XOR
The bitwise XOR operator is indicated by a caret (
^
) and, of course, works directly on the binary form of
numbers. Bitwise XOR is different from bitwise OR in that it returns 1 only when exactly one bit has a
value of 1. Here is the truth table:
40
Chapter 2
05_579088 ch02.qxd 3/28/05 11:35 AM Page 40

Free JavaScript Editor     Ajax Editor