Bitwise in JavaScript

Posted by yellowDog on 2018-05-14

自己封装的一个补 0 函数

因为 log 打印不出来那么多的 0,位运算中的左移啥的看不清楚

折腾了挺久的呢,赶紧去写留任的题目了 orz…还想学一波用 canvas 画一个爱心呢…

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
//Zero Fill
const binary = (decimal = 0) => {
if (decimal.toString(2) >= 0) {
let bin = decimal.toString(2);
if (bin.length < 32) {
let arr = bin.split(" ");
let remainStr = `0`.repeat(32 - bin.length);
arr.unshift(remainStr);
return arr.join("");
}
} else {
let transformBin = (~decimal).toString(2);
if (transformBin.length < 32) {
let arr = transformBin.split(" ");
let remainStr = `0`.repeat(32 - transformBin.length);
arr.unshift(remainStr);
let newResult = arr.join("").split("");
var brr = [];
for (var i in newResult) {
if (newResult[i] == "1") {
brr[i] = i;
}
if (newResult[i] == "0") {
newResult[i] = "1";
}
}
var crr = brr.filter(x => typeof x == "string").map(y => Number(y));
for (var c in crr) {
newResult[crr[c]] = "0";
}
return newResult.join("");
}
}
};

Bitwise NOT(~)

1
2
3
4
5
6
7
8
9
10
11
const a = 25;
const b = ~a;
const c = -a - 1;

console.time(`b`);
console.log(b); //-26
console.timeEnd(`b`); //2.306ms

console.time(`c`);
console.log(c);
console.timeEnd(`c`); //2.449ms

位运算更接近底层吧,速度快那么一丢丢


Bitwise AND(&)

两位都是 1 => return 1

1
2
3
4
5
6
7
8
9
const d = 25;
const e = 3;
console.log(binary(25));
00000000000000000000000000011001;
console.log(binary(3));
00000000000000000000000000000011;
console.log(binary(d & e));
00000000000000000000000000000001;
console.log(d & e); //1

Bitwise OR(|)

任一位是 1 => return 1

1
2
3
4
5
6
7
console.log(binary(d));
00000000000000000000000000011001;
console.log(binary(e));
00000000000000000000000000000011;
console.log(binary(d | e));
00000000000000000000000000011011;
console.log(d | e); //27

Bitwise XOR

只有一位是 1 => return 1

1
2
3
4
5
6
7
console.log(binary(d));
00000000000000000000000000011001;
console.log(binary(e));
00000000000000000000000000000011;
console.log(binary(d ^ e));
00000000000000000000000000011010;
console.log(d ^ e); //26

Left Shift (<<)

所有位左移指定的位数

1
2
3
4
5
const f = 2;
console.log(binary(f));
00000000000000000000000000000010;
console.log(binary(f << 9));
00000000000000000000010000000000;

Signed Right Shift (>>)

符号位保留,其他位指定右移的位数

1
2
3
4
5
6
console.log(binary(2));
00000000000000000000000000000010;
console.log(binary(64));
00000000000000000000000001000000;
console.log(binary(64 >> 5));
00000000000000000000000000000010;

Unsigned Right Shift (>>>)

所有的位都指定右移的位数

1
2
3
4
console.log(binary(-64));
11111111111111111111111111000000;
console.log(binary(-64 >>> 5));
00000111111111111111111111111110;