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