To a computer, everything is a number. Understanding the hidden secrets of numbers and how they are represented in a computer’s hardware is key to writing efficient and bug-free code. At the lowest level, all data is stored as a series of on/off switches, or bits, using a system called binary.
Table of Contents
💻 Binary and Numeral Systems
The numeral system we use every day is decimal (base-10). Computers use binary (base-2), which has only two digits: 0 and 1.
- Each position in a binary number represents a power of two (1, 2, 4, 8, 16, 32, etc.).
- The binary number
1011
is calculated as (1*8) + (0*4) + (1*2) + (1*1) = 11 in decimal. - Other important systems for programmers are hexadecimal (base-16), which uses digits 0-9 and letters a-f, and octal (base-8). These are often used as a more readable shorthand for binary.
💻 2’s Complement and Negative Numbers
How does a computer represent a negative number like -85 in binary? It uses a clever system called 2’s complement. For an 8-bit number, this is the process:
- Take the positive binary value of 85:
01010101
. - Invert all the bits (0s become 1s and 1s become 0s). This is the 1’s complement:
10101010
. - Add one to the result. This is the 2’s complement:
10101011
.
This binary pattern now represents -85. This system is elegant because it allows the computer to perform subtraction using the same addition circuitry.
💻 Data Types and Size
In many languages, you need to specify the data type of a number, such as `int` (integer) or `float` (decimal number). This tells the compiler how much memory to allocate. An 8-bit unsigned integer (`uint8`) can store values from 0 to 255. A 32-bit integer (`int32`) can store over 4 billion values. Choosing the right data type is important for memory efficiency and preventing overflow errors where a number becomes too large for its container.
More Topics
- Python Project Guide: NumPy & SciPy: For Science!
- Python Project Guide: Times, Dates & Numbers
- Python Project Guide: Making Scripts
- Python Project Guide: Build an FTP Client & Server
- Python Project Guide: Using Functions in Python 3
- Python Project Guide: How to Get Started with Python 3
- Coding Concepts Explained: Avoid Common Coding Mistakes