Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do the operators ">>" (double arrow) and "|" (single pipe) mean in JavaScript?

Tags:

javascript

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!

like image 200
benhowdle89 Avatar asked May 02 '12 22:05

benhowdle89


People also ask

What does single pipe mean in JavaScript?

A single pipe is a bit-wise OR. Performs the OR operation on each pair of bits. a OR b yields 1 if either a or b is 1. JavaScript truncates any non-integer numbers in bitwise operations, so its computed as 0|0 , which is 0.

What does this || mean in JavaScript?

The logical OR ( || ) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values.

What is single & in JavaScript?

The single ampersand operator (&) evaluates both sides of the operator before arriving at its answer. The double ampersand operator (&& – also known as the conditional-AND operator) evaluates the RHS only if the LHS is true. It short-circuits the evaluation so it doesn't have to evaluate the RHS if it doesn't have to.

What do double arrows mean in C++?

We have seen how the double arrows (<<) of the cout show that the information is going "out" to the monitor. In a similar way, the double arrows (>>) of the cin (pronounced see-in) show characters flowing "into" the program. The arrows point the way.


1 Answers

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".

like image 64
Niet the Dark Absol Avatar answered Sep 22 '22 15:09

Niet the Dark Absol