benhowdle89 - 8 months ago 37

Javascript Question

I saw this in some JS code:

`index = [`

ascii[0] >> 2,

((ascii[0] & 3) << 4) | ascii[1] >> 4,

((ascii[1] & 15) << 2) | ascii[2] >> 6,

ascii[2] & 63

];

I'd quite like to know what a lot of this means. Specifically ">>", a single pipe "|" and the "&" symbol on the last line?

Much appreciated!

Answer

`x >> y`

means to shift the bits of `x`

by `y`

places to the right (`<<`

to the left).

`x | y`

means to compare the bits of `x`

and `y`

, putting a `1`

in each bit if either `x`

or `y`

has a `1`

in that position.

`x & y`

is the same as `|`

, except that the result is `1`

if BOTH `x`

and `y`

have a `1`

.

Examples:

```
#left-shifting 1 by 4 bits yields 16
1 << 4 = b00001 << 4 = b10000 = 16
#right-shifting 72 by 3 bits yields 9
72 >> 3 = b1001000 >> 3 = b1001 = 9
#OR-ing
8 | 2 = b1000 | b0010 = b1010 = 10
#AND-ing
6 & 3 = b110 & b011 = b010 = 2
```

For more information, search Google for "bitwise operators".