A computer stores everything (numbers, text, pictures, programs) as bits: tiny switches that are either 0 or 1. Eight bits make a byte, the smallest piece of memory with its own address. With n bits you can write 2ⁿ different patterns: 8 bits give 256, 32 bits about 4.3 billion.
How big is each type?
#include <stdio.h>
int main(void) {
printf("char %zu byte\n", sizeof(char));
printf("short %zu bytes\n", sizeof(short));
printf("int %zu bytes\n", sizeof(int));
printf("long long %zu bytes\n", sizeof(long long));
printf("double %zu bytes\n", sizeof(double));
printf("int * %zu bytes\n", sizeof(int *));
int marks[10];
printf("int[10] %zu bytes\n", sizeof marks);
return 0;
}sizeof tells you how many bytes a type takes. On the computers StepVioz models (64-bit Linux, as on most servers and laptops):
| Type | Bytes | Bits | Range (signed) |
|---|---|---|---|
char | 1 | 8 | -128 to 127 |
short | 2 | 16 | -32,768 to 32,767 |
int | 4 | 32 | about ±2.1 billion |
long, long long | 8 | 64 | about ±9.2 × 10¹⁸ |
double | 8 | 64 | about 15 significant digits |
| any pointer | 8 | 64 | an address |
Seeing the bits
#include <stdio.h>
int main(void) {
int n = 13;
printf("%d in binary: ", n);
for (int i = 7; i >= 0; i--) {
int bit = (n >> i) & 1;
printf("%d", bit);
}
printf("\n");
return 0;
}This program prints the 8 bits of a number, from the highest to the lowest. (n >> i) & 1 moves bit i to the end and keeps only it. 13 is 00001101: 8 + 4 + 1. Each bit position is worth twice the one to its right: 128, 64, 32, 16, 8, 4, 2, 1.
Units. A kilobyte (KB) is 1000 bytes, and a kibibyte (KiB) 1024 bytes; memory sizes usually use powers of 2, so "8 GB of RAM" is really 8 GiB. Network speeds count bits: 100 Mbps is about 12.5 megabytes per second.
Quick check
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.