0

I have been recently reading this book, "Supercharged Javascript Graphics", and it is just awesome. It has some really interesting concepts and examples using html5 canvas element and other graphics. It also uses the jquery library and teaches how to create own plugins. In most of his examples however he uses bitwise operators and I am having trouble understanding them. He does explain their use but not entirely. The most used in his examples are:

       x >> 0
       x << y
       x >>> 0
       x & y
       x | y
       x^y

I am having some trouble understanding their use and their benefit, so I just want to know what is their equivalent using regular operators. How can I replace x >> y with something using like x%y or something in that sort.

lomas09
  • 1,114
  • 4
  • 12
  • 28
  • They explain what they do but the only clear example is x>>y. Also they do not go into detail of performance and their advantage – lomas09 May 07 '13 at 16:46
  • That link should be required reading but doesn't directly apply to JavaScript, so no dup in my eyes. – Kelly S. French May 07 '13 at 21:36

1 Answers1

2

Here's an explanation of each. In all cases, the operators convert their arguments to integer values if necessary. The result is always an integer value (or NaN if either argument is not convertible to an integer value).

x >> 0

This shifts 0 bits to the right, filling in on the left with the sign bit. It is a trick used to truncate x to an integer. (It is the same as Math.floor(x) if x is not negative, and the same as Math.ceil(x) if x is not positive.)

x << y

This shifts y bits to the left, filling in on the right with zero. It is equivalent to multiplying by 2y. It behaves somewhat unexpectedly when y < 0: it uses the bottom five bits of the two's complement representation of y as a positive shift value.

x >>> 0

This shifts x by nothing at all, but is the result of converting x to an unsigned integer value. (For instance, (-1) >>> 0 is 4294967295 = 232-1.)

x & y

This takes the bit-wise AND of the values in x and y. Each bit of the result is 1 if and only if the corresponding bits of x and y are both one.

x | y

This takes the bit-wise OR of the values in x and y. Each bit of the result is 1 if and only if one or both of the corresponding bits of x and y is one.

x^y

This takes the XOR of the values in x and y. Each bit of the result is 1 if and only if the corresponding bits of x and y are different.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521