Decimal to Binary
Convert a positive decimal integer to binary.
What is Decimal to Binary?
Repeated division by two produces binary digits from least significant to most significant.
Important points
- Compile with warnings enabled and fix every warning.
- Know the lifetime and type of every value.
- Validate input and keep array bounds explicit.
C and C++ code examples
main.c
#include <stdio.h>
int main(void) {
unsigned number = 13, value = number; int bits[32], count = 0;
// Store remainders generated from right to left.
do { bits[count++] = value % 2; value /= 2; } while (value);
printf("%u = ", number); while (count) printf("%d", bits[--count]); puts("");
}
13 = 1101
C++
main.cpp
#include <bitset>
#include <iostream>
#include <string>
int main() {
unsigned number = 13;
// Remove leading zeroes from a fixed-width bitset string.
std::string bits = std::bitset<32>(number).to_string();
bits.erase(0, bits.find_first_not_of('0'));
std::cout << number << " = " << bits << '\n';
}
13 = 1101
C and C++ comparison
Store remainders and print them in reverse order because division discovers the final digit first.
C
C exposes small procedural APIs and makes representation details explicit.
C++
C++ retains the low-level model while adding safer library types and abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add invalid and boundary-value inputs.
- Compile with -Wall -Wextra -Wpedantic.
- Move reusable declarations into a header and implementation file.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges