This is a zero-fill right shift, where one or more zero bits are added from the left, causing the rightmost bits to be discarded.
|
Decimal |
Binary |
|
5 |
00000000000000000000000000000101 |
|
5 >>> 1 |
00000000000000000000000000000010 (2) |
| let x = 5 >>> 1; |
Binary numbers with a single bit set are straightforward to comprehend.
|
Binary Representation |
Decimal value |
|
00000000000000000000000000000001 |
1 |
|
00000000000000000000000000000010 |
2 |
|
00000000000000000000000000000100 |
4 |
|
00000000000000000000000000001000 |
8 |
|
00000000000000000000000000010000 |
16 |
|
00000000000000000000000000100000 |
32 |
|
00000000000000000000000001000000 |
64 |
Setting additional bits reveals the binary pattern more clearly.
|
Binary Representation |
Decimal value |
|
00000000000000000000000000000101 |
5 (4 + 1) |
|
00000000000000000000000000001101 |
13 (8 + 4 + 1) |
|
00000000000000000000000000101101 |
45 (32 + 8 + 4 + 1) |
JavaScript binary numbers are stored in two’s complement format, meaning that a negative number is represented as the bitwise NOT of the number plus one.
|
Binary Representation |
Decimal value |
|
00000000000000000000000000000101 |
5 |
|
11111111111111111111111111111011 |
-5 |
|
00000000000000000000000000000110 |
6 |
|
11111111111111111111111111111010 |
-6 |
|
00000000000000000000000000101000 |
40 |
|
11111111111111111111111111011000 |
-40 |
| function dec2bin(dec){ return (dec >>> 0).toString(2); } |
| function bin2dec(bin){ return parseInt(bin, 2).toString(10); } |