forked from akshitagit/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbit_manipulation.js
More file actions
39 lines (30 loc) · 1.01 KB
/
bit_manipulation.js
File metadata and controls
39 lines (30 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//Bit Manipulation in javascript
// Function to get the bit at the ith position
function getBit(num, i)
{
// Return true if the ith bit is set. Otherwise return false
return ((num & (1 << i)) != 0);
}
// Function to set the ith bit of the given number num
function setBit(num, i)
{
// Sets the ith bit and return the updated value
return num | (1 << i);
}
// Function to clear the ith bit of the given number N
function clearBit(num, i)
{
// Create the mask for the ith bit unset.
let mask = ~(1 << i);
return num & mask;
}
// Driver code for given number N
let N = 90;
document.write("The bit at the 3rd position is: " +
(getBit(N, 3) ? '1' : '0') + "</br>");
document.write("The value of the given number " +
" after setting the bit at " +
" MSB is: " + setBit(N, 0) + "</br>");
document.write("The value of the given number " +
" after clearing the bit at " +
" MSB is: " + clearBit(N, 0) + "</br>");