tags:

views:

70

answers:

2

I'm reviewing some javascript code and the programmer uses >> in a few places. I tried to search on google but couldn't find what this operand / operator does. So here I be. Code example below:

var triplet=(((binarray[i>>2]>>8*(i%4))&0xFF)<<16)|(((binarray[i+1>>2]>>8*((i+1)%4))&0xFF)<<8)|((binarray[i+2>>2]>>8*((i+2)%4))&0xFF);
+1  A: 

The << and >> are common bitwise operators.

<< is left shift and
>> is right shift.

For example:

i << 2

will shift the value of i for 2 bits to the left.

You can find out more here (got to bitwise operators section): http://docs.rinet.ru/ProPauk/ch23.htm#BinaryOperators

gligoran
+2  A: 

>> is the right-shift operator, << is the left-shift operator. They operate on integers as follows:

00001000b >> 1 = 00000100b
00001000b << 1 = 00010000b

In other words:

num >> 1 = num / 2
num >> 2 = num / 4
.
.
.
num >> n = num / 2^n

Likewise:

num << 1 = num * 2
num << 2 = num * 4
.
.
.
num << n = num * 2^n
Salman A
An important thing to note is that `>>` used on a `signed` type will sign-extend, that is, it will make the left-most bit the same as the previous left-most bit, so the sign is maintained. Thus `(-1 >> 1) == -1`. For an unsigned type, the left-most bit is set to 0: `((unsigned)-1 >> 1) = 0x7fffffff` on a 4-byte `int` platform.
Mike DeSimone