Main Page

Signed right shift

Note that left shift preserves the sign of the number it’s operating on. For instance, if –2 is shifted to the
left by 5 spaces, it becomes –64, not positive 64. “But isn’t the sign stored in the 32nd bit?” you ask. Yes it
is, but that is behind the scenes of ECMAScript. The developer can never have access to that 32nd bit
directly. Even printing out a negative number as a binary string shows the negative sign (for instance,
–2 is displayed as –10 instead of 10000000000000000000000000000010).
Signed right shift
The signed right shift is represented by two
greater-than
signs (
>>
) and shifts all bits in a 32-bit number to
the right while preserving the sign (positive or negative); signed right shift is the exact opposite of left
shift. For example, if 64 is shifted to the right five bits, it becomes 2:
var iOld = 64; //equal to binary 1000000
var iNew = iOld >> 5; //equal to binary 10 with is decimal 2
Once again, when bits are shifted, the shift creates empty bits. This time, the empty bits occur at the left
of the number, but after the sign bit (see Figure 2-7). Once again, ECMAScript fills these empty bits with
the value in the sign bit to create a complete number.
Figure 2-7
Unsigned right shift
The unsigned right shift is represented by three greater-than signs (
>>>
) and shifts all bits in an
unsigned 32-bit number to the right. For numbers that are positive, the effect is the same as a signed
right shift. Using the same example as for the signed right shift example, if 64 is shifted to the right five
bits, it becomes 2:
var iOld = 64; //equal to binary 1000000
var iNew = iOld >>> 5; //equal to binary 10 with is decimal 2
For numbers that are negative, however, something quite different happens. You see, the unsigned right
shift operator fills all empty bits with the value contained in the 32nd bit. For positive numbers, this bit
is 0; so the empty bits are filled with zero. For negative numbers, however, this bit is 1, meaning that all
empty bits are filled with 1. Because the result of unsigned right shift is an unsigned 32-bit number, you
end up with a very large number. For example, if you shift –64 to the right by five bits, you end up with
2147483616. How does this happen?
00000000000000000000000001000000
The number 64
"Secret" sign bit
00000000000000000000000000000010
The number 64 shifted to the right 5 bits (the number 2)
Padded with zeros
42
Chapter 2
05_579088 ch02.qxd 3/28/05 11:35 AM Page 42


JavaScript EditorFree JavaScript Editor     Ajax Editor


©

R7