## JavaScript 位运算符

& 5 & 1 0101 & 0001  1 0001
| 5 | 1 0101 | 0001  5 0101
~ ~ 5  ~0101  10 1010
^ 亦或 5 ^ 1 0101 ^ 0001  4 0100
<< 0填充左移位 5 << 1 0101 << 1  10 1010
>> 有符号右移位 5 >> 1 0101 >> 1   2 0010
>>> 0填充右移位 5 >>> 1 0101 >>> 1   2 0010

~00000000000000000000000000000101 将返回 11111111111111111111111111111010

0 & 00
0 & 10
1 & 00
1 & 11

4 位实例:

1111 & 00000000
1111 & 00010001
1111 & 00100010
1111 & 01000100

1位实例:

0 | 00
0 | 1
1 | 01
1 | 11

4 位结果:

1111 | 00001111
1111 | 00011111
1111 | 00101111
1111 | 01001111

1位实例:

0 ^ 00
0 ^ 1
1 ^ 01
1 ^ 1

4 为实例:

1111 ^ 00001111
1111 ^ 00011110
1111 ^ 00101101
1111 ^ 01001011

## JavaScript 位操作

JavaScript 按位运算在32位有符号整数.

## JavaScript 按位与 (&)

500000000000000000000000000000101
100000000000000000000000000000001
5 & 100000000000000000000000000000001 (1)
```var x = 5 & 1;
```

## JavaScript 按位或 (|)

500000000000000000000000000000101
100000000000000000000000000000001
5 | 100000000000000000000000000000101 (5)
```var x = 5 | 1;
```

## JavaScript 按位亦或 (^)

500000000000000000000000000000101
100000000000000000000000000000001
5 ^ 100000000000000000000000000000100 (4)
```var x = 5 ^ 1;
```

## JavaScript 按位取反 (~)

500000000000000000000000000000101
~511111111111111111111111111111010 (-6)
```var x = 5 ^ 1;
```

## JavaScript 左移位 (<<)

500000000000000000000000000000101
5 << 100000000000000000000000000001010 (10)
```var x = 5 << 1;
```

## JavaScript 右移位 (>>)

-511111111111111111111111111111011
-5 >> 111111111111111111111111111111101 (-3)
```var x = -5 >> 1;
```

## JavaScript (零填充) 右移位 (>>>)

(零填充) 右移位:

500000000000000000000000000000101
5 >>> 100000000000000000000000000000010 (2)
```var x = 5 >>> 1;
```

## 32位有符号整数

000000000000000000000000000000011
000000000000000000000000000000102
000000000000000000000000000001004
000000000000000000000000000010008
0000000000000000000000000001000016
0000000000000000000000000010000032
0000000000000000000000000100000064

000000000000000000000000000001015 (4 + 1)
0000000000000000000000000010100040 (32 + 8)
0000000000000000000000000010110145 (32 + 8 + 4 + 1)

000000000000000000000000000001015
11111111111111111111111111111011-5
0000000000000000000000000010100040
11111111111111111111111111011000-40

## 十进制转换为二进制

```function dec2bin(dec){
return (dec >>> 0).toString(2);
}
```

## 二进制转换为十进制

```function bin2dec(bin){
return parseInt(bin, 2).toString(10);
}
```