Skip to content

Commit f345f7e

Browse files
feat: add bitwise operator
1 parent fc74abf commit f345f7e

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

part1 (Basics)/14_bitwise.js

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// Bitwise Operator
2+
/*
3+
<< Shifts the bits to left
4+
>> Shifts the bits to right
5+
~ Bitwise inversion (one's complement)
6+
& Bitwise logical AND
7+
| Bitwise logical OR
8+
^ Bitwise exclusive or
9+
*/
10+
11+
/*
12+
<< (Left Shift)
13+
Shifts bits to the left, adding zeros from the right.
14+
Example:
15+
5 << 1 = 10
16+
(5 in binary: 0101 → shifted left: 1010 → 10 in decimal)
17+
*/
18+
console.log(5 << 1); // Output: 10
19+
20+
/*
21+
>> (Right Shift)
22+
Shifts bits to the right, keeping the sign (for signed numbers).
23+
Example:
24+
10 >> 1 = 5
25+
(10 in binary: 1010 → shifted right: 0101 → 5 in decimal)
26+
*/
27+
console.log(10 >> 1); // Output: 5
28+
29+
/*
30+
~ (Bitwise NOT)
31+
Inverts the bits (one's complement).
32+
Example:
33+
~5 = -6
34+
(5 in binary: 0000000000000101 → inverted: 1111111111111010 → -6 in decimal)
35+
*/
36+
console.log(~5); // Output: -6
37+
38+
/*
39+
& (Bitwise AND)
40+
Compares each bit of two numbers, returns 1 only if both bits are 1.
41+
Example:
42+
5 & 3 = 1
43+
(5: 0101, 3: 0011 → result: 0001)
44+
*/
45+
console.log(5 & 3); // Output: 1
46+
47+
/*
48+
| (Bitwise OR)
49+
Compares each bit, returns 1 if either bit is 1.
50+
Example:
51+
5 | 3 = 7
52+
(5: 0101, 3: 0011 → result: 0111)
53+
*/
54+
console.log(5 | 3); // Output: 7
55+
56+
/*
57+
^ (Bitwise XOR)
58+
Returns 1 if bits are different, 0 if same.
59+
Example:
60+
5 ^ 3 = 6
61+
(5: 0101, 3: 0011 → result: 0110)
62+
*/
63+
console.log(5 ^ 3); // Output: 6

0 commit comments

Comments
 (0)