liveBook · Manning

Two's complement

As explained in JavaScript in Depth

A binary numeral representation for signed integers in which negative values are encoded by bitwise complement plus one.

Why does an eight-bit encoding of −1 contain nothing but 1s? Ordinary binary uses each bit position as a power of two, which accounts for nonnegative whole numbers but not negative ones. Two's complement gives signed integers a binary encoding while preserving ordinary binary addition. section 3.1.1 section 3.5

To encode a negative value in a fixed number of bits, write its positive magnitude in binary, flip every bit, then add 1. For example, in eight bits, 2 is 00000010; flipping its bits gives 11111101, and adding 1 gives 11111110 for −2. The most significant bit signals a negative value, but the remaining bits are not simply its magnitude. section 3.1.1 section 3.5

Table 3.2 Binary addition showing why -1 is represented as all 1s
Bit position
7
6
5
4
3
2
1
0
-1
1
1
1
1
1
1
1
1
1
0
0
0
0
0
0
0
1
Carry
1
1
1
1
1
1
1
 
Result
0
0
0
0
0
0
0
0

Eight-bit addition makes the choice of encoding visible: 11111111 (−1) plus 00000001 (1) produces 00000000, with the carry passing through the bit positions. section 3.1.1

Keep the encoding distinct from JavaScript's usual numeric representation. JavaScript Numbers are Binary64 floating-point values; two's complement explains signed-integer encoding, not the layout of every Number. V8 can separately optimize integers in its SMI range. section 3.1.1 section 3.5

How JavaScript in Depth covers it

How deep it goes
Works through bit flipping, adding one, and eight-bit addition without treating two's complement as the representation of every JavaScript Number.
Examples
Uses eight-bit encodings, including the addition of −1 and 1, to make the representation observable.
What it assumes
Introduces bits, byte positions, and bit flipping before using them to explain signed values.
What you can do after
Evaluate/understand why a negative integer can participate in ordinary binary addition and why that does not describe every JavaScript Number.
How it connects
Connects binary notation and signed integers to binary addition, Binary64 floating-point values, and V8's SMI optimization.

Also explained in

Compare how 6 books explain two's complement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.