Course contentsShow
← C
Lesson 689 of 1,21910. Input and OutputFree lesson

Printing hex and octal values

Printing hex and octal values

What you'll learn: How to use specialized format specifiers to display integers in base-16 (hexadecimal) and base-8 (octal) notation.

Different lenses for the same number

Computers love binary, but humans usually stick to base-10 (decimal). However, when you are working with memory addresses or low-level hardware flags, decimal feels clunky. Imagine looking at a color in a photo editor. You could describe a deep blue as "red: 0, green: 0, blue: 255," but programmers often prefer the shorthand #0000FF. That shorthand is hexadecimal.

In C, the printf() function acts like a lens. The actual value stored in your variable doesn't change, but you can change how it looks on your screen simply by swapping your format specifiers.

Using %x and %o

To print a value in hexadecimal, we use %x (lowercase) or %X (uppercase). To print in octal, we use %o.

Think of these like specialized filters on a camera. If you have the number 255, the %d filter shows you "255." The %x filter shows you "ff," and the %o filter shows you "377."

#include <stdio.h>

int main() {
    int myNumber = 2023;

    // Decimal (Base 10)
    printf("Decimal: %d\n", myNumber);

    // Octal (Base 8)
    printf("Octal:   %o\n", myNumber);

    // Hexadecimal (Base 16) - lowercase
    printf("Hex (l): %x\n", myNumber);

    // Hexadecimal (Base 16) - uppercase
    printf("Hex (U): %X\n", myNumber);

    return 0;
}

Adding the "Hash" flag

Sometimes, looking at a raw hex number like 7e7 is confusing—is that a word or a number? To make it clear, we often use the # flag (e.g., %#x). This tells printf to automatically add a prefix: 0x for hex or 0 for octal. It’s like putting a label on a jar so you know exactly what’s inside without guessing the measurement system.

Using %#x would turn ff into 0xff, which is the standard way programmers write hexadecimal in their code.

Key takeaway

Use %x for hexadecimal and %o for octal to view the same integer through different mathematical lenses.