Number systems: binary, octal and hexadecimal

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.

DecimalBinaryOctalHex
91001119
10101012A
15111117F
16100002010
25511111111377FF

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;
}
Open in compiler

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;
}
Open in compiler

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 0x2D for hex, 055 for octal (a leading 0!), and 0b101101 for 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

1. What is binary 1010 in decimal?
2. What is 255 in hexadecimal?
3. In C, what is the value of 010?

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.