↑

Main Page

# ECMAScript outputs

Figure 2-5

Negative numbers are also stored in binary code, but in a format called

two’s complement

. The two’s com-

plement of a number is calculated in three steps:

1.

Determine the binary representation of the non-negative version (for example, to find –18, first

determine the binary representation of 18).

2.

Find the one’s complement of the number, which essentially means that every 0 must be

replaced with 1 and vice versa.

3.

Add 1 to the one’s complement.

To determine the binary representation for –18, you must first take the binary representation of 18,

which is:

0000 0000 0000 0000 0000 0000 0001 0010

Next, take the one’s complement, which is the inverse:

1111 1111 1111 1111 1111 1111 1110 1101

Finally, add 1 to the one’s complement:

1111 1111 1111 1111 1111 1111 1110 1101

1

---------------------------------------

1111 1111 1111 1111 1111 1111 1110 1110

So, the binary equivalent of –18 is 1111 1111 1111 1111 1111 1111 1110 1110. Keep in mind that the devel-

oper has no access to bit 31 when dealing with signed integers.

The interesting thing about negative integers is that conversion to a binary string does not show the

two’s complement form. Instead, ECMAScript outputs the standard binary code for the number ’s abso-

lute value preceded by a minus sign. For example:

var iNum = -18;

alert(iNum.toString(2)); //outputs “-10010”

This code outputs only

“-10010”

instead of the two’s complement in order to protect bit 31 from being

accessed. To put it simply, ECMAScript aims to deal with integers in such a simple way that developers

need not spend any time worrying about their usage.

10010

(2

4

x1) + (2

3

x0) + (2

2

x0) + (2

1

x1) + (2

0

x0)

16 + 0 0

0

2

+++

18

38

Chapter 2

05_579088 ch02.qxd 3/28/05 11:35 AM Page 38

Free JavaScript Editor
Ajax Editor

©

↓