Bitwise operators perform operations directly on the binary representation of numbers.
They are used in:
Computers store numbers in binary (base-2), where each bit represents a power of two.
Decimal | Binary |
---|---|
0 | 0000 |
1 | 0001 |
2 | 0010 |
3 | 0011 |
4 | 0100 |
5 | 0101 |
6 | 0110 |
7 | 0111 |
8 | 1000 |
9 | 1001 |
10 | 1010 |
Bitwise operations manipulate these individual bits.
Each bit is set to 1 only if both input bits are 1.
1001 (9)
& 0011 (3)
------
0001 (1)
Each bit is set to 1 if at least one input bit is 1.
1001 (9)
| 0011 (3)
------
1011 (11)
Each bit is set to 1 only if the input bits are different.
1001 (9)
^ 0011 (3)
------
1010 (10)
Inverts each bit.
~ 1001 (9)
------
0110 (-10)
Note: Because of two’s complement representation, inverting all bits causes the number to become negative, and the formula becomes ~n equals -(n + 1)
Shifts bits left, multiplying by 2^n.
0011 (3)
<< 1 // Shifting left by 1 bit (multiplying by 2)
------
0110 (6)
Shifts bits right, dividing by 2^n, while preserving the sign.
0011 (3)
>> 1 // Shifting right by 1 bit (dividing by 2)
------
0001 (1)
Shifts bits right like >>
, but always fills with zeros instead of preserving
the sign bit.
function isOdd(number) {
return (number & 1) == 1;
}
If the last bit is 1, the number is odd.
let a = 5;
let b = 3;
a = a ^ b;
b = a ^ b;
a = a ^ b;
No extra memory needed.
We can set each bit to represent a permission.
const READ = 0b001;
const WRITE = 0b010;
const EXEC = 0b100;
const userPermissions = READ | WRITE; // 011
To check if the user has WRITE permission:
if (userPermissions & WRITE) {
// has write access
}
n << 2; // Multiplies by 4
n >> 3; // Divides by 8
Find this post helpful? Subscribe and get notified when I post something new!