﻿ Bitwise NOT ﻿

Main Page

# Bitwise NOT

Unsigned integers, on the other hand, treat the final bit just like the other bits. In this mode, the 32nd bit
doesn’t represent the sign of the number but rather the value 2
31
. Because of this extra bit, unsigned inte-
gers range in value from 0 to 4294967295. For numbers less than or equal to 2147483647, unsigned inte-
gers look the same as positive signed integers; numbers greater than 2147483647 require the use of bit 31
(which is always 0 in a signed positive integer). Unsigned integers only return the significant bits when
they are converted into a binary string.
Remember, all integer literals are stored as signed integers by default. Unsigned integers can only be cre-
ated by using one of the ECMAScript bitwise operators.
Bitwise NOT
The bitwise NOT is represented by a tilde (~) and is one of just a few ECMAScript operators related to
binary mathematics. The bitwise NOT is a three-step process:
1.
The operand is converted to a 32-bit number.
2.
The binary form is converted into its one’s complement.
3.
The one’s complement is converted back to a floating-point number.
Example:
var iNum1 = 25; //25 is equal to 00000000000000000000000000011001
var iNum2 = ~iNum1; //convert to 111111111111111111111111111100110
The bitwise NOT essentially negates a number and then subtracts 1 from it, so 25 becomes –26. Really,
the same effect can be achieved by doing this:
var iNum1 = 25;
var iNum2 = -iNum1 – 1;
Bitwise AND
The bitwise AND operator is indicated by the ampersand (
&
) and works directly on the binary form of
numbers. Essentially, bitwise AND lines up the bits in each number and then, using the following rules,
performs an AND operation between the two bits in the same position:
Bit from First Number Bit from Second Number
Result
1
1
1
1
0
0
0
1
0
0
0
0
For example, if you wanted to AND the numbers 25 and 3 together, the code looks like this:
39
ECMAScript Basics
05_579088 ch02.qxd 3/28/05 11:35 AM Page 39

Free JavaScript Editor     Ajax Editor