Main Page

Bitwise operators

The unary minus converted the string
into the number
in the previous code (unary minus
also acts the same way as unary plus regarding hexadecimal and decimal values, but it also negates
the value).
Bitwise operators
The following set of operators work on numbers at their very base level, with the 32 bits that represent
them. Before examining these operators, I begin with a more detailed look into integers in ECMAScript.
Integers revisited
ECMAScript integers come in two specific flavors: signed (allowing both positive and negative values)
and unsigned (allowing only positive numbers). In ECMAScript, all integer literals are signed by
default. But what exactly does this mean?
Signed integers use the first 31 bits to represent the numeric value of the integer, whereas the 32nd bit
represents the sign of the number, 0 for positive or 1 for negative. The number values can range from
–2147483648 to 2147483647.
You can store signed integers in binary form in two different ways, one for positive numbers and one for
negative numbers. Positive numbers are stored in true binary format, with each of the first 31 bits repre-
senting a power of 2, starting with the first bit (called bit 0), which represents 2
; the second bit (bit 1)
represents 2
, and so on. If any bits are unused, they are filled with 0s and essentially ignored. For exam-
ple, the number 18 is represented as shown in Figure 2-4.
Figure 2-4
The binary version of 18 uses only the first five bits, which are the significant bits for this number. When
converting a number into a binary string (as discussed earlier), you see only the significant bits:
var iNum = 18;
alert(iNum.toString(2)); //outputs “10010”
This code outputs only
instead of the whole 32-bit representation. The other bits really aren’t
important because using just these five bits makes possible to determine the decimal value (Figure 2-5).
The number 18
Bit 31
Bit 0
ECMAScript Basics
05_579088 ch02.qxd 3/28/05 11:35 AM Page 37

JavaScript EditorFree JavaScript Editor     Ajax Editor