-
Notifications
You must be signed in to change notification settings - Fork 0
/
bitOperation.js
71 lines (60 loc) · 1.64 KB
/
bitOperation.js
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const checkNthBitIsSet = (x, n) => x & (1 << n);
const setNthBit = (x, n) => x | (1 << n);
const unsetNthBit = (x, n) => x & ~(1 << n);
const toggleNthBit = (x, n) => x ^ (1 << n);
const turnOffTheRightmost1Bit = x => x & (x - 1);
const isolateTheRightmost1Bit = x => x & (-x);
const rightPropagateTheRightmost1Bit = x => x | (x-1);
const isolateTheRightmost0Bit = x => ~x & (x+1)
const turnOnTheRightmost0Bit = x => x | (x+1)
const setNthBit64 = (x, n) => {
// console.log(x,n)
let hi = 0x80000000
let lo = 0x7fffffff
let high = ~~(x / hi);
let low = x & lo;
// console.log(`set -- high: ${high}, low: ${low}`);
if (n > 31) {
return setNthBit(high, n-31) * hi + low;
} else if( n == 31) {
if (high & 1 === 1) {
return x;
} else {
return (hi * 1)+x;
}
} else {
return high * hi + setNthBit(low, n);
}
}
const unsetNthBit64 = (x, n) => {
// console.log(x,n)
let hi = 0x80000000
let lo = 0x7fffffff
let high = ~~(x / hi);
let low = x & lo;
// console.log(`unset -- high: ${high}, low: ${low}`);
if (n > 31) {
return unsetNthBit(high, n-31) * hi + low;
} else if( n == 31) {
if (high & 1 === 1) {
return x - hi;
} else {
return x;
}
} else {
return high * hi + unsetNthBit(low, n);
}
}
module.exports = {
checkNthBitIsSet,
setNthBit,
unsetNthBit,
toggleNthBit,
turnOffTheRightmost1Bit,
isolateTheRightmost1Bit,
rightPropagateTheRightmost1Bit,
isolateTheRightmost0Bit,
turnOnTheRightmost0Bit,
setNthBit64,
unsetNthBit64,
}