We write numbers in base 10: each digit is worth ten times the digit to its right. Computers use base 2 (binary). Programmers also use base 16 (hexadecimal, "hex"), because one hex digit is exactly 4 bits, so a byte is two hex digits.
| Decimal | Binary | Octal | Hex |
|---|---|---|---|
| 9 | 1001 | 11 | 9 |
| 10 | 1010 | 12 | A |
| 15 | 1111 | 17 | F |
| 16 | 10000 | 20 | 10 |
| 255 | 11111111 | 377 | FF |
Converting by repeated division
#include <stdio.h>
int main(void) {
int n = 45;
int base = 2;
int digits[32];
int count = 0;
int x = n;
while (x > 0) {
digits[count++] = x % base; // the remainder is the next digit
x /= base;
}
printf("%d in base %d: ", n, base);
for (int i = count - 1; i >= 0; i--) printf("%d", digits[i]);
printf("\n");
printf("hex %x, octal %o\n", n, n);
return 0;
}To write n in base b, divide by b again and again: the remainders, read from the last to the first, are the digits. 45 ÷ 2 gives remainders 1, 0, 1, 1, 0, 1, so 45 is 101101 in binary. The program stores the digits in an array, then prints them backwards.
Back to decimal, and in C
#include <stdio.h>
int main(void) {
char digits[] = "101101";
int base = 2;
int value = 0;
for (int i = 0; digits[i] != '\0'; i++) {
value = value * base + (digits[i] - '0');
}
printf("%s in base %d is %d\n", digits, base, value);
printf("0x2D = %d, 055 = %d\n", 0x2D, 055);
return 0;
}To read digits in base b, start from 0 and, for each digit, multiply by b and add the digit: 101101 gives ((((1×2+0)×2+1)×2+1)×2+0)×2+1 = 45.
C understands these bases directly:
- write
0x2Dfor hex,055for octal (a leading 0!), and0b101101for binary in newer compilers; - print with
%x(hex) and%o(octal).
Hex shortcut. Group binary digits in fours from the right: 1011 0110 is B6. Addresses in the visualizer, like 0x7fffefdc, are written in hex.
Quick check
Practice problems for this lesson
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.