Bitwise Operators


Computers actually deal with data in terms of bits, that is, in terms of binary values , 0 and 1. For example, the number 9 is really stored in binary as 1001. JavaScript gives you access to the actual binary bits of the data it's working on with its bitwise operators. This probably won't concern you very much, and if not, feel free to skip on. For the sake of completeness, however, I'll include these details here.

You can see the JavaScript bitwise operators and what they do in Table 2.8.

Table 2.8. JavaScript Bitwise Operators

Operator

Usage

Does This

Bitwise AND

x & y

Places a one in each bit position of the result for which the corresponding bits of both operands are ones.

Bitwise OR

x y

Places a one in each bit position of the result for which the corresponding bits of either or both operands are ones.

Bitwise XOR

x ^ y

Places a one in each bit position of the result for which the corresponding bits of either, but not both , operands are ones.

Bitwise NOT

~ x

Flips the bits of its operand.

Left shift

x << y

Shifts x by y bits to the left (shifting in zeros from the right).

Sign-propagating right shift

x >> y

Shifts x by y bits to the right (not preserving bits shifted off).

Zero-fill right shift

x >>> y

Shifts x by y bits to the right, not preserving bits shifted off, and shifting in zeros from the left.

These operators treat numeric values as 32-bit values; each bit in one operand is paired with the corresponding bit in the other operand. Here's an example: 4 is 0100 in binary, and 1 is 0001, so using bitwise OR, , on these two yields 4 1 = 0100 0001 = 0101 , or 5. Here's what that looks like in code:

(Listing 02-11.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Working With Bitwise OR          </TITLE>      </HEAD>      <BODY>          <H1>Working With Bitwise OR</H1>          <SCRIPT LANGUAGE="JavaScript">          <!--             var result = 4  1              document.write("4  1 = " + result)          // -->          </SCRIPT>       </BODY>  </HTML> 

Figure 2.8 shows the results of the code ( 4 1 = 5 ).

Figure 2.8. Using the bitwise OR operator.

graphics/02fig08.gif

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted (shifting a bit means moving it left or right to the adjoining places in the binary number). The direction of the shift operation is controlled by the operator used. Shift operators shift the bits of their operands and convert those operands to 32-bit integers. For example, 9 << 1 gives a result of 18, because 1001 shifted one bit to the left becomes 10010, which is 18.



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net