How to Print Binary Numbers in C: Bitwise Methods, C23 %b Specifier, and Examples

目次

1. Introduction

What is Binary? Why is it Important?

The binary system is the most fundamental numerical representation in the world of computers. Using only the digits 0 and 1, it represents data in memory and the state of hardware. In programming, binary numbers are used in bit manipulation, state management, binary file analysis, and many other scenarios.

C language is widely used for writing efficient programs. However, the standard library does not provide a direct way to display numbers in binary format. In this article, we will explain how to display binary numbers in C language from the basics, making it easy for beginners to understand, while also covering practical code examples and the latest C23 standard.

2. Basics of Number Representation in C | Decimal, Hexadecimal, Octal

Explanation of Standard Format Specifiers

In C, you can use the printf function to print numbers on the screen. Here are the common format specifiers and their usage:

  • %d: Decimal (default integer representation)
  • %o: Octal (often represented with a leading 0)
  • %x / %X: Hexadecimal (lowercase/uppercase format)

For example, running the following code prints the number in different formats:

#include <stdio.h>

int main() {
    int num = 42;

    printf("Decimal: %d\n", num);
    printf("Octal: %o\n", num);
    printf("Hexadecimal: %x\n", num);

    return 0;
}

Output Example:

Decimal: 42
Octal: 52
Hexadecimal: 2a

Why There is No Binary Format Specifier

The C standard library does not include a format specifier for binary output. The main reason lies in historical design choices. Since C was originally developed for system programming, efficient memory manipulation was prioritized over binary output.

侍エンジニア塾

3. How to Display Binary in C (with Code Examples)

Using Bitwise Operations

Binary output in C can be implemented using bitwise operations. Below is an example that prints an 8-bit number in binary format:

#include <stdio.h>

void printBinary(int num) {
    for (int i = 7; i >= 0; i--) {
        printf("%d", (num >> i) & 1);
    }
    printf("\n");
}

int main() {
    int num = 42;
    printf("Binary: ");
    printBinary(num);

    return 0;
}

Output Example:

Binary: 00101010

Code Explanation

  • (num >> i): Shifts num right by i bits, moving the target bit to the least significant position.
  • & 1: Extracts the least significant bit.
  • printf: Prints each bit in sequence.

This approach is simple, flexible, and works with any integer size.

A Generic Function

For more flexibility, you can create a generic function that supports any bit width:

#include <stdio.h>

void printBinaryGeneric(unsigned int num, int bitWidth) {
    for (int i = bitWidth - 1; i >= 0; i--) {
        printf("%d", (num >> i) & 1);
    }
    printf("\n");
}

int main() {
    int num = 42;
    printf("16-bit Binary: ");
    printBinaryGeneric(num, 16);

    return 0;
}

Output Example:

16-bit Binary: 0000000000101010

4. New Feature in C23: %b Specifier

Overview of the %b Specifier

Until now, C did not provide a standard format specifier for binary output. However, C23 introduced a new specifier:

  • %b: Used to display numbers in binary format.

This means you no longer need custom functions with bitwise operations—printing binary can be done easily.

Example: Displaying Binary with C23 %b Specifier

Here is a basic example using the %b specifier:

#include <stdio.h>

int main() {
    int num = 42;

    printf("Binary: %b\n", num);

    return 0;
}

Output Example:

Binary: 101010

Key Benefits of %b

  1. Simplicity
  • No need for loops or bitwise operations. Clean, minimal code.
  1. Readability
  • Consistent with other format specifiers, making code easier to read.

Compiler Support

Since C23 is new, not all compilers support %b yet. Current status:

  • Supported Compilers
  • GCC: Partial support starting from version 12.
  • Clang: Supported in the latest versions.
  • Unsupported Compilers
  • Older GCC, Clang versions, and some proprietary compilers are not supported yet.

What If Your Environment Does Not Support %b?

If your compiler doesn’t support C23 or the %b specifier, try these alternatives:

1. Use a Custom Function

Use the bitwise method shown earlier (e.g., printBinary).

2. Use a Third-Party Library

Some libraries, such as glib, provide utility functions for binary output.

3. Upgrade to a C23-Compatible Environment

Consider installing the latest compilers to take advantage of new C23 features.

5. Visual Guide: Binary Representation and Bitwise Operations

5.1 Conversion Flow from Decimal to Binary

Here’s how to convert decimal to binary step by step, using 42 as an example:

Example: Convert Decimal 42 to Binary

42 ÷ 2 = 21 ... 0
21 ÷ 2 = 10 ... 1
10 ÷ 2 = 5  ... 0
5  ÷ 2 = 2  ... 1
2  ÷ 2 = 1  ... 0
1  ÷ 2 = 0  ... 1
--------------
Binary: 101010

Reversing the remainders gives 101010, which is the binary representation of 42.

5.2 Visual Explanation of Shift Operations

Right Shift (>>)

Shifts all bits to the right.

  • Example: Shifting 101010 (42 in decimal) right by 1 → 010101 (21 in decimal).
Original: 101010
Right >>: 010101

Left Shift (<<)

Shifts all bits to the left.

  • Example: Shifting 101010 (42 in decimal) left by 1 → 1010100 (84 in decimal).
Original: 101010
Left << : 1010100

5.3 Bitmasking

Example: Turn On the 4th Bit (OR Operation)

  00001010  (Original)
| 00010000  (Mask)
------------
  00011010  (Result)

Usage: Enables specific bits, commonly used in flag management.

6. FAQ (Frequently Asked Questions)

Q1: Why doesn’t C have a standard binary format specifier?

A:
When C was first designed, performance was prioritized. Decimal, octal, and hexadecimal formats were included, but binary was considered too niche. With C23 introducing %b, binary output is now standardized.

Q2: What if I can’t use the C23 %b specifier?

A:
Options include:

  1. Write a custom function using bitwise operations.
  2. Install a modern compiler such as GCC 12+ or the latest Clang.
  3. Use third-party libraries that provide binary output utilities.

Q3: Is it true that Python and Java can print binary easily?

A:
Yes. Both languages have built-in functions:

Python Example

num = 42
print(bin(num))  # Output: 0b101010

Java Example

int num = 42;
System.out.println(Integer.toBinaryString(num));  // Output: 101010

Q4: Why doesn’t right shift work as expected?

A:
Two possible issues:

  • Signed integers: Right shifting a signed int may preserve the sign bit (arithmetic shift). Use unsigned int to avoid this.
  • Invalid shift width: Shifting beyond the number of bits of the type is undefined behavior.

Q5: How can I ensure a fixed number of digits in binary output?

A:
Use a fixed-width function:

void printBinaryFixed(unsigned int num) {
    for (int i = 15; i >= 0; i--) {
        printf("%d", (num >> i) & 1);
    }
    printf("\n");
}

Q6: Do developers really use binary output in real projects?

A:
Yes, in these scenarios:

  • Hardware control (device drivers)
  • Binary data analysis (file formats, network protocols)
  • Debugging flags and states

Q7: Any good resources for learning bitwise operations?

A:
Recommended resources:

  • Books: "C Programming: A Beginner’s Guide" (intro + bitwise ops), "System Programming in C" (practical usage).
  • Online: GeeksforGeeks (detailed tutorials), Qiita (Japanese community articles).

7. Conclusion

Summary

This article explained how to print binary numbers in C, from basics to advanced techniques. Below is a comparison of methods:

MethodDescriptionProsCons
Custom Function (Bitwise)Manually implementedFlexible, works with any bit widthMore code required
C23 %b SpecifierStandard format specifierSimple, highly readableRequires C23-compatible environment
Third-Party LibrariesUse external utilitiesSaves timeMay add environment dependencies

Next Steps for Readers

  • Try the code examples in your environment to deepen understanding.
  • Apply bitwise operations for flag management and debugging.

Tips for Further Learning

  1. Review Bitwise Fundamentals
  • Study shift operators and logical operations (AND, OR) to improve programming efficiency.
  1. Experiment with C23 Features
  • Test the new %b specifier and explore modern C standards.
  1. Compare with Other Languages
  • Try binary output in Python or Java to understand differences with C.