How to use Bitwise OR operator in Javascript
Description
The bitwise OR operator is represented by a single pipe character |
and works on two numbers.
Bitwise OR follows the rules in this truth table:
BIT FROM FIRST NUMBER | BIT FROM SECOND NUMBER | RESULT |
---|---|---|
1 | 1 | 1 |
1 | 0 | 1 |
0 | 1 | 1 |
0 | 0 | 0 |
A bitwise OR operation returns 1 if at least one bit is 1. It returns 0 only if both bits are 0.
Example
var result = 25 | 3;
console.log(result); //27
Actual calculation
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
The code above generates the following result.
Example 2
The following code shows how to use Binary Flags with binary operators.
var FIELD_A = 0x1; // 00001
var FIELD_B = 0x2; // 00010
var FIELD_C = 0x4; // 00100
var FIELD_D = 0x8; // 01000
var FIELD_E = 0x10; // 10000
//from w w w . j av a2s.co m
var fieldsSet = FIELD_A | FIELD_C | FIELD_E;
if ((fieldsSet & FIELD_A) && (fieldsSet & FIELD_C)) {
console.log("Fields A and C are set");
}
The code above generates the following result.