Writing an Integer in Base Two

A binary numeral adds powers of two at positions whose bits are one.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Decode four positions
  2. Encode a value
  3. Convert by powers and by remainders
  4. Declare the width when leading zeros affect storage

Decode four positions

The unsigned bit pattern 1011 denotes \(8+0+2+1=11\). Starting at the right uses weights 1, 2, 4, and 8. This is a positional representation, like the quotient and remainder process used for decimal digits.

Encode a value

Thirteen is \(8+4+1\), so its shortest ordinary binary spelling is 1101. Use leading zeros to fill a declared field width when needed. A fixed-width field supplies that width.[1]

Convert by powers and by remainders

Forty-five is \(32+8+4+1\), putting ones at positions five, three, two and zero. The same representation follows from repeated division by two and reading the remainders backward. Using both methods gives a way to catch missed place values. See recursion over digits.

Powers:   32 16  8  4  2  1
Bits:      1  0  1  1  0  1
Remainders when dividing: 1,0,1,1,0,1
Result: 101101

Declare the width when leading zeros affect storage

The mathematical value remains forty-five after padding to eight bits. A binary file format can require all eight positions. Zero is the case where the division loop may generate no bits unless handled explicitly. See unsigned ranges.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩