Have you ever wondered how computers “think” and process numbers? At the core of it all, computers use the binary number system, which consists solely of 0s and 1s, also known as base 2. This fundamental system is used to represent everything from simple text to complex images in a format that machines can understand.
On the other hand, we humans use the decimal system, which includes ten digits (0 through 9) and is more intuitive for everyday tasks like counting, measuring, and calculating. Even though programming languages let us work comfortably in decimal, computers convert these values into binary behind the scenes to perform operations, and then convert the result back to decimal for us to see.
In this blog, we will cover everything from the differences between binary and decimal numbering systems, the need for converting decimal to binary, and how to implement them in your code using various popular programming languages such as C++, Java, Python, and more.
Table of Contents:
What is the Decimal Number System?
Whether you are aware of it or not, you use the decimal number system on a daily basis. It is what we use to count and calculate anything from money to latitude and longitude, and everything in between, using the digits 0 through 9, where the position of a digit determines its value, and each position represents a power of 10.
What is the Binary Number System?
The binary number system is the fundamental language of computers, made up entirely of 0s and 1s. It encodes everything from text and numbers to images in a form that machines can interpret. Each digit, known as a bit, represents a power of 2 based on its position in the sequence.
In binary, every bit (binary digit) represents a switch, ON (1) or OFF (0), making it ideal for electronic circuitry and digital computing.
Why Convert Decimal to Binary?
While most modern computers and programming languages allow us to work with decimal numbers, all calculations are ultimately performed in binary. This is because computers are built on digital circuits that recognise only two states: ON (1) and OFF (0).
For instance, if you input 13 + 7 into a program, the decimal values are first converted into binary, then processed by the machine, and finally converted back to decimal to display the result. In the next section, we’ll explore the mathematical algorithm used to perform this decimal-to-binary conversion.
How to Convert Decimal to Binary
There is a surprisingly simple trick that most programming languages use behind the hood to convert decimal numbers to binary. Simply keep dividing by 2. While it may sound basic, this is an incredibly powerful method. Let’s break it down step by step:
Decimal to Binary Conversion in Different Programming Languages
Now that we have a basic understanding of the binary and decimal number systems, and the core algorithm used for their conversion. Let’s jump to some decimal-to-binary conversion examples.
1. C++
C++ is a great place to start learning decimal to binary conversions due to the fact that you get complete control over memory and logic. Let’s look at three different ways to convert a decimal to binary in C++.
Manual conversion using loops:
This is the classic approach using the division-by-2 algorithm we discussed earlier. We’ll store and print remainders as we go.
Code:
#include <iostream>
using namespace std;
void decimalToBinary(int num) {
if (num == 0) {
cout < 0) {
binary = to_string(num % 2) + binary;
num /= 2;
}
cout << "Binary: " << binary << endl;
}
int main() {
int number = 13;
cout << "Decimal: " << number << endl;
decimalToBinary(number);
return 0;
}
Output:
Decimal: 13
Binary: 1101
Using arrays or stacks
Arrays and stacks are also a great alternative to using strings. All you have to do is collect all the remainders in one of the data structures and print them in reverse order. This method is closer to how binary is handled at the hardware level.
Code:
#include <iostream>
using namespace std;
void decimalToBinary(int num) {
int binary[32]; // enough for 32-bit integers
int index = 0;
if (num == 0) {
cout < 0) {
binary[index++] = num % 2;
num /= 2;
}
cout <= 0; i--) {
cout << binary[i];
}
cout << endl;
}
int main() {
int number = 13;
cout << "Decimal: " << number << endl;
decimalToBinary(number);
return 0;
}
Output:
Decimal: 13
Binary: 1101
Using bitset
C++’s <bitset> library makes this task incredibly simple and is perfect when you want fixed-width binary output.
Code:
#include <iostream>
#include
using namespace std;
int main() {
int number = 13;
bitset binary(number); // 8-bit representation
cout << "Decimal: " << number << endl;
cout << "Binary: " << binary << endl;
return 0;
}
Output:
Decimal: 13
Binary: 00001101
2. Python
Python is known for its readability and easy syntax. This applies when converting decimal numbers to binary numbers as well because Python provides a built-in method. Let’s discuss the manual approach first.
Manual conversion using loops
Let’s start with a manual implementation using a loop to convert decimal to binary in Python.
Code:
def decimal_to_binary(n):
if n == 0:
return "0"
binary = ""
while n > 0:
remainder = n % 2
binary = str(remainder) + binary
n = n // 2
return binary
# Example usage
number = 13
print("Decimal:", number)
print("Binary:", decimal_to_binary(number))
Output:
Decimal: 13
Binary: 1101
We use loops here to divide the number by 2 and collect remainders as we go along. We then prepend the result to a string to get the binary numbers in the correct order.
Using built-in bin() function
We can also use the built-in bin() function to do the same instantly without all the added logic.
Code:
number = 13
binary = bin(number)
print("Decimal:", number)
print("Binary:", binary)
Output:
Decimal: 13
Binary: 0b1101
The output for binary starts with the prefix 0b, which notates that this is a binary number.
3. Java
Java’s verbose syntax and strong type system will allow us to deeply explore how the algorithm works step by step. As always, let’s explore the manual method first.
Manual conversion
This method for decimal to binary in Java gives you full control and helps reinforce the logic behind binary representation.
Code:
public class DecimalToBinary {
public static void main(String[] args) {
int number = 13;
System.out.println("Decimal: " + number);
System.out.println("Binary: " + convertToBinary(number));
}
static String convertToBinary(int n) {
if (n == 0) return "0";
String binary = "";
while (n > 0) {
int remainder = n % 2;
binary = remainder + binary;
n = n / 2;
}
return binary;
}
}
Output:
Decimal: 13
Binary: 1101
Using Integer.toBinaryString()
Java, like most modern programming languages, provides an in-built function to make the conversion to binary easier.
Code:
public class DecimalToBinary {
public static void main(String[] args) {
int number = 13;
String binary = Integer.toBinaryString(number);
System.out.println("Decimal: " + number);
System.out.println("Binary: " + binary);
}
}
Output:
Decimal: 13
Binary: 1101
4. JavaScript
JavaScript also provides 2 ways to convert decimal numbers to binary. The manual way, if you have a deep understanding of the logic and the built-in function that takes care of all the heavy lifting.
Manual method
Let’s use a while loop with a string concatenation to implement the logic ourselves.
Code:
function decimalToBinary(n) {
if (n === 0) return "0";
let binary = "";
while (n > 0) {
binary = (n % 2) + binary;
n = Math.floor(n / 2);
}
return binary;
}
Example usage
let number = 13;
console.log("Decimal:", number);
console.log("Binary:", decimalToBinary(number));
Output:
Decimal: 13
Binary: 1101
By dividing the number by 2 at each iteration of the loop, we can build the binary number from right to left by prepending the results.
Using Number.prototype.toString(2)
Calling toString(2) on a number converts it into a string representing the number in base 2, which is binary.
Code:
let number = 13;
let binary = number.toString(2);
console.log("Decimal:", number);
console.log("Binary:", binary);
Output:
Decimal: 13
Binary: 1101
5. C
C’s low-level control over memory and operations makes it a great choice if you want to understand how decimal to binary conversion is done under the hood. Let’s first look at a manual implementation using loops and arrays, since C does not provide built-in binary formatting, so we must implement the logic manually.
Manual loop method
We’ll use an array to store binary digits (remainders), then print them in reverse order to convert decimal to binary in C.
Code:
#include <stdio.h>
void decimalToBinary(int num) {
if (num == 0) {
printf("0");
return;
}
int binary[32]; // Array to store binary digits
int index = 0;
while (num > 0) {
binary[index] = num % 2;
num = num / 2;
index++;
}
// Print binary number in reverse order
for (int i = index - 1; i >= 0; i--) {
printf("%d", binary[i]);
}
}
int main() {
int number = 13;
printf("Decimal: %d\n", number);
printf("Binary: ");
decimalToBinary(number);
printf("\n");
return 0;
}
Output:
Decimal: 13
Binary: 1101
We repeatedly divide the number by 2 as previously discussed and store the remainders in an array. And since the first remainder we get is the least significant bit, we print the array in reverse to get the correct binary representation.
Using recursion
We can also use recursion to achieve the same result without the use of arrays. Recursion will allow us to print the binary digits as the call stack unwinds, which acts as a natural reversal of the order of bits, leaving us with the most significant bit to the least significant bit.
Code:
#include <stdio.h>
void decimalToBinary(int num) {
if (num == 0)
return;
decimalToBinary(num / 2); // Recursive call with quotient
printf("%d", num % 2); // Print remainder after returning
}
int main() {
int number = 13;
printf("Decimal: %d\n", number);
printf("Binary: ");
if (number == 0) {
printf("0");
} else {
decimalToBinary(number);
}
printf("\n");
return 0;
}
Output:
Decimal: 13
Binary: 1101
Comparison of Decimal to Binary Methods Across Languages
Now that we’ve seen how each language handles decimal-to-binary conversion, here’s a quick cheat sheet that may come in handy.
Language | Manual Conversion | Built-in Conversion |
C++ | Loops, Arrays, Recursion | bitset |
Python | While loop | bin() |
Java | While loop | Integer.toBinaryString() |
JavaScript | While loop | toString(2) |
C | Loops, Arrays, Recursion | N/A |
Common Mistakes to Avoid
We have so far covered the difference between decimal and binary and their conversion. While trying to implement the examples on your own, remember to avoid these common mistakes that beginners tend to make.
- Incorrect loop conditions: Forgetting to exit the loop when it hits 0 can result in an infinite loop, potentially crashing your program.
- Misunderstanding integer division: In most languages, dividing integers like 5 / 2 gives 2, not 2.5. This is essential for the conversion logic to work.
- Forgetting edge cases like 0 and negative numbers: Not handling 0 correctly may result in an empty binary string. Negative numbers require a signed binary representation, which is a separate topic.
Conclusion
So far, we have covered the decimal number system, the binary number system, and the algorithms used to convert one to the other. We also learned how to implement them using the top 5 most popular programming languages. Another number system worth mentioning, which is not in the scope of this article, is the octal number system. Learning all the number systems, how they function, and how to convert between them at will is a valuable skill, not just for technical interviews, but for developing a deeper appreciation of how computers think.
Now that you know how decimal to binary conversion works across multiple languages, you can apply this knowledge confidently, whether you’re debugging, studying for exams, or simply building smarter code.
How to Convert Decimal to Binary – FAQs
1. What is the fastest way to convert a decimal to binary in programming?
The fastest way to convert a decimal number to binary depends on various factors such as the programming language you are using and the context.
Built-in functions are the optimal choice if your goals are high performance and simplicity.
- Python:
bin(13)
returns '0b1101'
- Java:
Integer.toBinaryString(13)
returns '1101'
- JavaScript:
13..toString(2)
returns '1101'
Using built-in functions makes your code more readable and scalable. However, if you’re working in C or C++, especially in lower-level or embedded contexts, built-in conversions may not be available. In that case, writing a custom function using loops or bitwise operators is the fastest and most practical method.
2. Are built-in functions better than arrays for decimal to binary conversion?
Learning to execute the conversion using loops will force you to get a greater understanding of the logic behind the conversion and make you a better developer overall. But if your goal is to write clean, efficient code, we suggest using a built-in function.
3. How to convert decimal to binary without using arrays or stacks?
Of course, many beginner-friendly implementations use just a string and a loop to execute the conversion. Here is an implementation in Python:
# Python example without array or stack
def decimal_to_binary(n):
binary = ""
while n > 0:
binary = str(n % 2) + binary
n = n // 2
return binary
This method works by prepending each binary digit (remainder) to a string, effectively reversing the order without using a separate data structure.
4. Is recursion necessary for binary conversion?
While recursion is a valid and elegant approach to converting decimal to binary, it is not the only one. Most decimal-to-binary conversions can be done using loops, which are easier to understand and more memory-efficient. That said, recursion offers a neat, minimal way to print binary digits in the correct order without needing to reverse anything.
5. Which is the best programming language for learning decimal to binary conversion?
There’s no one-size-fits-all answer; the best language is most often the one you already know. So, instead of asking which is the best programming language for number system conversion, ask how you can do it with the language that you already know.