Bits, floats, text and encodings

O(1)·O(1) space
Fit

Drag to pan; pinch or Ctrl+scroll to zoom; arrow keys pan once the picture has focus.

0011111111111111n = 127
  • Reference

The value 127 is non-negative, so this is plain binary with the top bit clear: 01111111.

The value 127 is non-negative, so this is plain binary with the top bit clear: 01111111.
  1. 1encode the number as plain or two’s-complement binary
  2. 2invert every bit
  3. 3add one to the inverted bits — that is the negation
  4. 4add one to the original number and see whether it still fits in 8 bits
Operations performed
1

Complexity

BestO(1)
AverageO(1)
WorstO(1)
Extra spaceO(1)
bits touched at n=1 predicts 1; this run took 1.

Two's complement

Two’s complement represents a signed integer in a fixed number of bits by giving the top bit negative place value: in 8 bits, the top bit is worth −128 and every other bit its ordinary positive value. A positive number is plain binary. A negative number’s encoding can be derived mechanically: invert every bit, then add one. Addition is ordinary unsigned binary addition, modulo the width — the circuit never knows or cares which numbers are "negative".

When it is the right choice

This is how essentially every processor represents a signed integer; there is no competing scheme in ordinary use to choose instead (sign-magnitude and ones’ complement exist, but are not what any reader’s own integers are doing).

How it works

Worth noticing

Cost

Best
O(1)
Average
O(1)
Worst
O(1)
Extra space
O(1)

Worth comparing

All bits algorithms