18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

ECMAScript Basics<br />

Unsigned integers, on the other hand, treat the final bit just like the other bits. In this mode, the 32nd bit<br />

doesn’t represent the sign of the number but rather the value 2 31 . Because of this extra bit, unsigned integers<br />

range in value from 0 to 4294967295. <strong>For</strong> numbers less than or equal to 2147483647, unsigned integers<br />

look the same as positive signed integers; numbers greater than 2147483647 require the use of bit 31<br />

(which is always 0 in a signed positive integer). Unsigned integers only return the significant bits when<br />

they are converted into a binary string.<br />

Remember, all integer literals are stored as signed integers by default. Unsigned integers can only be created<br />

by using one of the ECMAScript bitwise operators.<br />

Bitwise NOT<br />

The bitwise NOT is represented by a tilde (~) and is one of just a few ECMAScript operators related to<br />

binary mathematics. The bitwise NOT is a three-step process:<br />

1. The operand is converted to a 32-bit number.<br />

2. The binary form is converted into its one’s complement.<br />

3. The one’s complement is converted back to a floating-point number.<br />

Example:<br />

var iNum1 = 25; //25 is equal to 00000000000000000000000000011001<br />

var iNum2 = ~iNum1; //convert to 111111111111111111111111111100110<br />

alert(iNum2); //outputs “-26”<br />

The bitwise NOT essentially negates a number and then subtracts 1 from it, so 25 becomes –26. Really,<br />

the same effect can be achieved by doing this:<br />

var iNum1 = 25;<br />

var iNum2 = -iNum1 – 1;<br />

alert(iNum2); //outputs “-26”<br />

Bitwise AND<br />

The bitwise AND operator is indicated by the ampersand (&) and works directly on the binary form of<br />

numbers. Essentially, bitwise AND lines up the bits in each number and then, using the following rules,<br />

performs an AND operation between the two bits in the same position:<br />

Bit from First Number Bit from Second Number Result<br />

1 1 1<br />

1 0 0<br />

0 1 0<br />

0 0 0<br />

<strong>For</strong> example, if you wanted to AND the numbers 25 and 3 together, the code looks like this:<br />

39

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!