File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ //Bit Manipulation in javascript
2+
3+ // Function to get the bit at the ith position
4+ function getBit ( num , i )
5+ {
6+ // Return true if the ith bit is set. Otherwise return false
7+ return ( ( num & ( 1 << i ) ) != 0 ) ;
8+ }
9+
10+ // Function to set the ith bit of the given number num
11+ function setBit ( num , i )
12+ {
13+ // Sets the ith bit and return the updated value
14+ return num | ( 1 << i ) ;
15+ }
16+
17+ // Function to clear the ith bit of the given number N
18+ function clearBit ( num , i )
19+ {
20+
21+ // Create the mask for the ith bit unset.
22+ let mask = ~ ( 1 << i ) ;
23+ return num & mask ;
24+ }
25+
26+ // Driver code for given number N
27+ let N = 90 ;
28+
29+ document . write ( "The bit at the 3rd position is: " +
30+ ( getBit ( N , 3 ) ? '1' : '0' ) + "</br>" ) ;
31+
32+ document . write ( "The value of the given number " +
33+ " after setting the bit at " +
34+ " MSB is: " + setBit ( N , 0 ) + "</br>" ) ;
35+
36+ document . write ( "The value of the given number " +
37+ " after clearing the bit at " +
38+ " MSB is: " + clearBit ( N , 0 ) + "</br>" ) ;
39+
You can’t perform that action at this time.
0 commit comments