liveBook · Manning

Two's complement

As explained in Clojure: The Essential Reference

Two's complement is a binary representation of signed integers in which negative values are encoded by complementing the bits of their magnitudes and adding one.

Two's complement represents signed integers in binary: negative values use complemented magnitude bits plus one. It gives fixed-width integers a sign bit and makes overflow wrap from one extreme to the other. section 5.1 section 3.2.3

The representation determines several practical behaviors:

  • Arithmetic right shifts preserve the sign bit, padding negative values with ones; unsigned right shifts pad with zeros. section 3.2.3

Inspecting a negative shift

Integer/toBinaryString displays -147 as "11111111111111111111111101101101". Shifting it right by one produces "11111111111111111111111110110110", while shifting by two produces "11111111111111111111111111011011". The leading ones preserve the negative sign.

How Clojure: The Essential Reference covers it

How deep it goes
Works through 32-bit and 64-bit boundary layouts, then applies the representation to arithmetic and logical shifts.
Examples
Uses 32-bit and 64-bit boundary tables plus binary-string demonstrations of negative right shifts.
What you can do after
Evaluate signed overflow and interpret arithmetic versus unsigned right shifts in Clojure.
How it connects
Connects signed integers with integer overflow, bitwise operations, arithmetic shifting, logical shifting, and fixed-width numeric types.

Also explained in

Compare how 4 books explain two's complement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.