Decimal (base 10) is the everyday number system. Binary (base 2) uses only bits 0 and 1. Conversion means rewriting a decimal integer as a string of bits.
Remember
Divide by 2 → remainder is the next bit (LSB first)
Reverse the remainders → MSB … LSB binary string
Example: 13
13 ÷ 2 = 6 rem 1
6 ÷ 2 = 3 rem 0
3 ÷ 2 = 1 rem 1
1 ÷ 2 = 0 rem 1
Remainders (LSB→MSB): 1 0 1 1
Binary (MSB→LSB): 1101
Decimal
Binary
Check
0
0
special case
13
1101
8+4+1
42
101010
32+8+2
Approach
How to Convert Decimal to Binary in C++
Four clear steps — then pick a remainder loop or std::bitset.
Handle n == 0 by returning "0".
While n > 0, record n % 2 and set n = n / 2.
Reverse the collected remainders (or build the string from the front).
Or use std::bitset and trim leading zeros for a short answer.
Method
Idea
Time
Best for
Remainder loop
Divide by 2; reverse remainders
O(log n)
Interviews, learning place values
std::bitset
Fixed-width bits, then trim zeros
O(1) width / O(log n) trim
Production code, short answers
Pseudocode
Pseudocode
function DecimalToBinary(n):
if n == 0:
return "0"
bits = empty list
while n > 0:
bits.append(n mod 2)
n = n / 2
reverse bits
return join(bits)
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
Operation
Divide by 2; remainder is a bit
First remainder
LSB (rightmost bit)
Zero
Return "0" — do not skip
Built-in
std::bitset<32>(n).to_string()
Negatives
Usually restrict to n >= 0 in tutorials
Classic check
13 → 1101
Try it
Live Preview
Enter a nonnegative integer to see the remainder steps and the binary result.
Nonnegative integers (capped at 2147483647). Tap a chip or type a value.