Course contentsShow
← C
Lesson 119 of 1,2192. Variables and TypesFree lesson

Integer literals (Hex, Octal, Binary)

Integer literals (Hex, Octal, Binary)

What you'll learn: How to write numbers in different mathematical bases so your code is easier to read when dealing with hardware or memory.

Different ways to say "Ten"

In everyday life, we use Decimal (Base-10). When you type int x = 10;, the compiler assumes you are counting on ten fingers. However, computers "think" in powers of two. Sometimes, writing a number in decimal is actually more confusing than using its binary, hexadecimal, or octal equivalent.

Think of it like currency: you could describe a price as "one hundred pennies" or "one dollar." The value is the same, but the context makes one description much clearer than the other.

The Secret Prefixes

To tell the C compiler you aren't using decimal, you add a special prefix to the start of the number.

  1. Hexadecimal (Base-16): Use the prefix 0x. Hex is the "gold standard" for programmers because two hex digits represent exactly one byte. It uses 0–9 and A–F (where A=10 and F=15).
  2. Binary (Base-2): Use the prefix 0b. This is perfect when you want to visualize individual bits (on/off switches) inside a variable.
  3. Octal (Base-8): Use a leading 0 (zero). Be careful! If you write 012, C treats it as octal, which is actually 10 in decimal.

Coding in Different Bases

Here is how these look in action. Even though they look different to us, the computer stores them as the exact same electronic signals.

#include <stdio.h>

int main() {
    // All of these variables represent the number 15
    int decimal     = 15;   
    int hex         = 0xF;  // 0x prefix for Hexadecimal
    int binary      = 0b1111; // 0b prefix for Binary
    int octal       = 017;  // Leading 0 for Octal

    // They are mathematically equal
    if (decimal == hex && hex == binary && binary == octal) {
        printf("They are all the same value!\n");
    }

    return 0;
}

When to use them?

You will rarely use Octal in modern programming, but you will use Hex and Binary constantly when working with colors (like #FF5733), memory addresses, or hardware pins. Using 0b1010 is much more intuitive for a "pattern" of switches than writing 10.

Key takeaway

Use 0x for Hexadecimal, 0b for Binary, and a leading 0 for Octal to write numbers in the format that best fits your specific problem.