Numbers · beginner
C Program to Convert Decimal to Binary
Convert a decimal number to binary in C by storing remainders of division by 2 in an array, then with bitwise shifts that print all 8 or 32 bits.
- arrays
- while loop
- bitwise >> and &
- unsigned integers
printf has %d, %x and %o, but no binary format in C17, so converting to binary is a classic exercise. Dividing by 2 repeatedly gives the binary digits from right to left; storing them in an array lets the program print them in the right order.
The program
#include <stdio.h>
void print_binary(unsigned int n) {
char bits[32];
int count = 0;
do {
bits[count++] = (char)('0' + n % 2);
n /= 2;
} while (n > 0);
while (count > 0)
putchar(bits[--count]);
putchar('\n');
}
int main(void) {
print_binary(10);
print_binary(255);
print_binary(0);
return 0;
}1010
11111111
0How it works
- n % 2 is the next binary digit from the right; '0' + digit turns 0 or 1 into the character '0' or '1'.
- n /= 2 halves n; the do-while runs at least once, so 0 prints as "0".
- The digits were stored in reverse order, so the second loop prints the array backwards.
- unsigned int has at most 32 bits, so a 32-character array is always big enough.
Another way: Fixed width with bit shifts
Shifting right by i and masking with & 1 reads bit i directly. Looping from the highest bit down prints a fixed-width pattern, which is how bytes are usually shown.
#include <stdio.h>
int main(void) {
unsigned char byte = 10;
for (int i = 7; i >= 0; i--)
putchar((byte >> i) & 1 ? '1' : '0');
putchar('\n');
return 0;
}00001010Common mistakes
- Printing the remainders as they are produced, which shows the binary digits reversed.
- Using a signed int and right-shifting negative numbers, whose result is implementation-defined.
- Making the digit array too small for the largest value (an int can need 32 digits).
Try it yourself
- Convert binary text such as "1010" back to decimal.
- Print a number in base 8 and base 16 with the same method, then check with %o and %X.
Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 C examples, or write your own program in the online C Compiler.