Understanding binary representation
What you'll learn: How to visualize how computers store integers using only ones and zeros.
Before we can manipulate individual bits, we need to understand how the computer "sees" a number. In our daily lives, we use the decimal system (base-10), likely because we have ten fingers. Computers, however, are made of tiny electronic switches that can only be in two states: ON (1) or OFF (0). This is the binary system (base-2).
The light bulb analogy
Imagine a row of eight light bulbs. Each bulb represents a "bit" (a binary digit).
- If a bulb is OFF, it represents 0.
- If a bulb is ON, it represents 1.
In decimal, each position in a number represents a power of 10 (1s, 10s, 100s). In binary, each position represents a power of 2, starting from the right. For an 8-bit number (a char in C), the values of the bulbs from right to left are:
128, 64, 32, 16, 8, 4, 2, 1
Translating binary to decimal
To find the value of a binary number, you simply add up the values of the "ON" bulbs.
If we have the binary sequence 00001101:
- The 8 bulb is ON (1)
- The 4 bulb is ON (1)
- The 1 bulb is ON (1)
- All others are OFF (0)
Calculation: . So, 00001101 is just the number 13 in binary.
Why this matters in C
In C, we usually write numbers in decimal because it's easier for humans. However, the computer always stores them as these patterns of high and low voltages. When we start using bitwise operators in the next lesson, we will be reaching inside these numbers to flip those specific switches.
#include <stdio.h>
int main() {
// The computer stores these differently in memory,
// but represents the same underlying bits.
int myNumber = 13;
// In binary (mental visualization): 00000000 00000000 00000000 00001101
printf("The value is: %d", myNumber);
return 0;
}
By understanding that every integer is just a collection of "on" or "off" slots, you gain the power to write code that is extremely fast and memory-efficient.
Key takeaway
Binary is a base-2 system where each digit's value doubles as you move from right to left (1, 2, 4, 8...).