1

Possible Duplicate:
What do these operators do?

I'm working with some javascript for html 5's canvas. I'm looking at some existing code and I've come across the following:

element.height >> 1
element.width >> 1

Its used as part of some arithmetic.

I am using prototype.js as well, if this helps.

Community
  • 1
  • 1
Pete
  • 683
  • 1
  • 8
  • 17
  • 1
    [Rigt shift](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators#.3E.3E_(Sign-propagating_right_shift)). – rid Nov 12 '11 at 18:12
  • Should be bitwise shifting of the number. – Smamatti Nov 12 '11 at 18:13
  • Note that in general it's probably a bad idea to use shift operators for division/multiplication - the meaning is obscure to programmers who haven't been exposed to C/C++ etc and unlike in C they'll probably be slower than just using the normal operators:http://stackoverflow.com/questions/337355/javascript-bitwise-shift-of-long-long-number/337572#337572 – John Carter Nov 12 '11 at 19:40

5 Answers5

5

>> is the bitwise shifting operator. So >> 1 basically shifts the binary representation of the number on the left by one to the right. This is equal to an integer division by 2.

So element.height >> 1 equals to Math.floor( element.height / 2)

hugomg
  • 68,213
  • 24
  • 160
  • 246
poke
  • 369,085
  • 72
  • 557
  • 602
  • 1
    But note that JavaScript doesn't actually have integer division. If (for example) `n == 325`, then `n / 2 == 162.5`. – ruakh Nov 12 '11 at 18:26
3

It's a bitshift operator.

user229044
  • 232,980
  • 40
  • 330
  • 338
3

It's a sign-propagating right-shift; full explanation here: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators#.3E.3E_%28Sign-propagating_right_shift%29.

ruakh
  • 175,680
  • 26
  • 273
  • 307
2

Shifting (bitshift) operator.

1 << 1

This shifts the bitpattern 00000001 to the left once (padding with 0s)- you get 00000010, which is 2.

1 << 2

shifts it by two, so you get 00000100, which is 4.


It comes useful when implementing binary protocols, where only 2 bits can mean something. Using shifting you can strip out the rest.

Emil Ivanov
  • 37,300
  • 12
  • 75
  • 90
0

This is the sign-propagating right shift operator which shifts the digits of the binary representation of the first operand to the right by the number of places specified by the second operand, discarding any shifted off to the right. The copies of the leftmost bit are added on from the left, thereby preserving the sign of the number.

So in your case everything is shifted one place to the right.

FailedDev
  • 26,680
  • 9
  • 53
  • 73