Converting decimals to binary is perhaps one of those exercises that embrace computer science fundamental studies upon which the computer’s way of thinking can be mastered. In day-to-day life, we deal with decimals or base 10 (0 to 9), but computers use binary numbers base 2 (0 or 1 ) numbers. This decimal to binary program in C conversion process is very important, especially in programming, networking and data processing.
Number System
4 Major Types of Number Systems
1. Decimal Number System (Base-10)
The decimal system is the number system we use every day. It has ten digits from 0 to 9. Each digit's place in a number is important because it tells us how many tens, hundreds, or thousands it represents. For example, in 345, the 3 means 300, the 4 means 40, and the 5 means 5. All these add up to 345. This system works well for humans and day-to-day counting.
2. Binary Number System (Base-2)
The binary system is the language of computers. It only has two digits: 0 and 1. These represent off-and-on states in electronics. In binary, each place value is a power of 2. For example, the binary number 101 means 1x 4 (or )+ 0 x 2 (or + 1 x 1 (or When you add that up, 101 in binary equals 5 in decimal. Computers use binary because it’s simple and matches their internal circuits.
3. Octal Number System (Base-8)
The octal system uses eight digits: 0, 1, 2, 3, 4, 5, 6, and 7. Each place value in octal is a power of 8. For example, the octal number 123 means 1X64 (or 8^2) + 2 x 8 (or 8^1) +3 x 1 (or8^0). Adding these gives 83 in decimal. Octal is helpful in computing because it makes binary numbers shorter. Three binary digits can fit into one octal digit, making long binary numbers easier to read and write.
4. Hexadecimal Number System (Base-16)
The hexadecimal system uses sixteen symbols: 0 to 9 and A to F. A stands for 10, B for 11, and so on up to F, which is 15. Each place value in hexadecimal is a power of 16. For example, the hexadecimal number 1A means 1 x 16 (or 16^1) + 10 x 1 (or 16^0) . When you add these, 1A in hexadecimal equals 26 in decimal. Hexadecimal is often used in computing because it makes binary numbers shorter and easier to work with. One hexadecimal digit equals four binary digits.
Decimal Numbers in C
Decimal numbers are base-10 numbers, and these are the type we use in everyday life. In C programming, they're represented using the float or double data types. A float uses 4 bytes of memory and provides a precision of about 6-7 digits. If you need higher precision, double uses 8 bytes and offers around 15-16 digits of precision.
Binary Numbers in C
Binary numbers are base-2 numbers, made up of just 0s and 1s. In C, they're usually represented by the int or long int data types, which use 32 or 64 bits, respectively. To write a binary number in C, you use the prefix 0b followed by a sequence of 0s and 1s, like 0b1010.
Different Methods to Convert Decimal to Binary Programs in C
1. Division Method
The division method involves repeatedly dividing the decimal number by 2 and storing the remainder. These remainders represent the binary digits. The process continues until the quotient becomes 0. The binary number is then read by reversing the order of the remainders.
2. Stacks
Using stacks helps store binary digits (remainders) as they are calculated which allows for easy reversal. The decimal number is divided by 2 in a loop, and the remainders are pushed onto the stack. After the loop ends, the stack is popped to display the binary number in the correct order.
3. While Loop
A while loop is used to repeatedly divide the decimal number by 2, and store each remainder. The loop runs until the decimal number becomes 0. Binary digits are calculated in each iteration and either printed directly or stored for later use.
4. For Loop
A for loop performs the same task as a while loop but with defined initialization, condition, and increment/decrement in one statement. The loop divides the number by 2 and calculates remainders to derive the binary number step by step.
5. Bitwise Operators
Bitwise operators like & and >> can convert decimal to binary. The & 1 operation extracts the least significant bit, while >> shifts the bits to the right. This approach is efficient and avoids arithmetic operations like division.
6. Recursion
Recursion uses a function that repeatedly calls itself with the quotient of the number divided by 2. Each remainder is calculated and printed after the recursive call returns, and the binary number is displayed in the correct order.
7. User-Defined Function
A user-defined function encapsulates the logic of binary conversion. For example, a function can take the decimal number as input, it then handles the conversion process internally, and return or print the binary result.
8. Math Library
The math library can assist in binary conversion using logarithms and powers. For instance, base-2 logarithms can determine the highest bit position. It helps in manual binary representation without traditional loops or recursion.
9. Negative Numbers
Converting negative numbers to binary involves using two’s complement representation. First, calculate the binary form of the absolute value of the number. Then, flip all the bits (1 becomes 0 and 0 becomes 1), and add 1 to the result. This method is used in computer systems to represent signed integers.
10. Floating Decimals
For floating-point numbers, the integer part is converted using standard methods, and the fractional part is multiplied by 2 repeatedly. The integer parts of the results are recorded to derive the binary equivalent of the fractional part.
Algorithm to Convert Decimal to Binary Number in C
Here’s a step-by-step algorithm to convert a decimal number to binary in C:
- Declare integer variables to store the decimal number, quotient, remainder, and binary number.
- Read the decimal number from the user.
- Initialise the quotient with the decimal number.
- Initialise the binary number to 0.
- Loop while the quotient is not 0:
- Calculate the remainder by taking the modulus of the quotient with 2 (quotient % 2).
- Multiply the binary number by 10 and add the remainder to it.
- Update the quotient by dividing it by 2.
- Print the binary number.
Now let’s write some code for a C program to convert decimal to binary.
C Program to Convert Decimal to Binary Number Using FOR Loop
Algorithm:
1. Initialize Variables: Declare variables for the decimal number, remainder, and a binary array to store the binary digits.
2. Input Decimal Number: Prompt the user to enter a decimal number.
3. Convert to Binary:
- Use a for loop to divide the decimal number by 2 repeatedly.
- Store the remainder (0 or 1) in the binary array during each iteration.
- Update the decimal number by dividing it by 2 in each loop.
4. Output the Binary Number:
- Iterate through the binary array in reverse order.
- Print the binary digits to display the result.
Here’s the binary to decimal C code using For loop:
#include <stdio.h>
int main() {
int decimal, quotient, remainder;
int binary[32]; // Array to store binary digits (supports up to 32-bit numbers)
int i;
// Prompt the user for input
printf("Enter a decimal number: ");
scanf("%d", &decimal);
quotient = decimal;
i = 0;
// Convert decimal to binary using a for loop
for (; quotient > 0; i++) {
remainder = quotient % 2;
binary[i] = remainder;
quotient = quotient / 2;
}
// Print the binary number in reverse order
printf("Binary equivalent: ");
for (int j = i - 1; j >= 0; j--) {
printf("%d", binary[j]);
}
printf("\n");
return 0;
}
Output:
Enter a decimal number: 3
Binary equivalent: 11
=== Code Execution Successful ===
How the code works
- Input: The user enters a decimal number.
- Initialize: The quotient is set to the entered number.
- Conversion Loop:
- In each iteration, the number is divided by 2.
- The remainder (0 or 1) is stored in an array.
- The quotient is updated to match the division's result.
- Repeat until the quotient becomes 0.
- Reverse Output:
- The binary digits are stored in reverse order.
- Print the array elements backward to display the correct binary number.
C Program to Convert Decimal to Binary Number Using While Loop
Algorithm:
1. Initialize Variables: Declare variables for the decimal number, remainder, and binary number (initialized to 0).
2. Input Decimal Number: Ask the user to enter a decimal number.
3. Conversion Process:
- Start a while loop that runs as long as the decimal number is greater than 0.
- Inside the loop:
- Compute the remainder by dividing the decimal number by 2.
- Multiply the binary number by 10 and add the remainder to it to build the binary representation.
- Update the decimal number by dividing it by 2.
4.Output Binary Number: Print the binary result after the loop ends.
Here’s a binary to decimal C using the While loop:
#include <stdio.h>
int main() {
int decimal, quotient, remainder;
int binary[32]; // Array to store binary digits (supports up to 32-bit numbers)
int i = 0;
// Prompt the user for input
printf("Enter a decimal number: ");
scanf("%d", &decimal);
quotient = decimal;
// Convert decimal to binary using a while loop
while (quotient > 0) {
remainder = quotient % 2;
binary[i] = remainder;
quotient = quotient / 2;
i++;
}
// Print the binary number in reverse order
printf("Binary equivalent: ");
for (int j = i - 1; j >= 0; j--) {
printf("%d", binary[j]);
}
printf("\n");
return 0;
}
Output:
Enter a decimal number: 6
Binary equivalent: 110
=== Code Execution Successful ===
How the code works:
- Input: The user enters a decimal number.
- Initialize: The quotient is set to the input number, and the index i is initialised to 0.
- Conversion Loop: While the quotient is greater than 0:
- Calculate the remainder by taking quotient % 2.
- Store the remainder in the binary array.
- Update the quotient by dividing it by 2.
- Increment i to track the array index.
- Reverse Output:
- The binary digits are stored in reverse.
- Print the array elements in reverse order to get the correct binary number.
C Program to Convert Decimal to Binary Number Using Function
Algorithm:
1. Initialize Variables:
- Declare variables to store the decimal number, remainder, and an array to store the binary digits.
2. Input Decimal Number:
- Prompt the user to enter a decimal number.
3. Calculate Binary Digits:
- Start a for loop to iterate through the decimal number:
- Divide the decimal number by 2 and store the remainder.
- Store the remainder in the array for binary digits.
- Update the decimal number by dividing it by 2.
4. Reverse Binary Digits:
- After the loop finishes, print the array from the last element to the first (to reverse the binary digits).
5. Output the Binary Number:
- Print the binary number after all digits have been printed in the correct order.
Here’s the decimal to binary C using the function:
#include <stdio.h>
// Function to convert decimal to binary
void decimalToBinary(int decimal) {
int binary[32]; // Array to store binary digits (supports up to 32-bit numbers)
int i = 0;
// Convert decimal to binary
while (decimal > 0) {
binary[i] = decimal % 2;
decimal = decimal / 2;
i++;
}
// Print the binary number in reverse order
printf("Binary equivalent: ");
for (int j = i - 1; j >= 0; j--) {
printf("%d", binary[j]);
}
printf("\n");
}
int main() {
int decimal;
// Prompt the user for input
printf("Enter a decimal number: ");
scanf("%d", &decimal);
// Call the function to convert decimal to binary
decimalToBinary(decimal);
return 0;
}
Output:
Enter a decimal number: 8
Binary equivalent: 1000
=== Code Execution Successful ===
How the code works:
- Input: The user enters a decimal number.
- Function Call: The decimalToBinary function is called with the input decimal number as an argument.
- Inside Function:
- The function initialises an array to store binary digits.
- A while loop converts the decimal number to binary by dividing it by 2 and storing the remainder in the array.
- The quotient is updated after each division.
- Reverse Output:
- Once the conversion is complete, the binary digits are printed in reverse order.
- This ensures the correct binary number is displayed.
C Program to Convert Decimal to Binary Number Using For Stack
Algorithm:
1. Initialize Variables:
- Declare an integer array to represent the stack and a variable for the stack's top index.
2. Input Decimal Number:
- Prompt the user to input a decimal number.
3. Push Remainders onto Stack:
- Start a while loop that continues as long as the decimal number is greater than 0.
- Inside the loop:
- Divide the decimal number by 2 and compute the remainder.
- Push the remainder onto the stack (increment the stack's top index).
- Update the decimal number by dividing it by 2.
4. Pop and Print Binary Digits:
- After the loop finishes, start popping elements from the stack one by one.
- Print each popped value to form the binary number.
5. Output the Binary Number:
- The binary number is printed as the stack elements are popped, which displays the binary representation of the decimal number.
In this, we’ll look into decimal to binary C code using for stack:
#include <stdio.h>
// Function to convert decimal to binary using stack (array)
void decimalToBinary(int decimal) {
int binary[32]; // Array to store binary digits (supports up to 32-bit numbers)
int top = -1; // Stack top pointer
// Convert decimal to binary using a for loop and stack
for (int quotient = decimal; quotient > 0; quotient /= 2) {
top++; // Increment stack pointer
binary[top] = quotient % 2; // Push remainder onto stack
}
// Print the binary number by popping it from the stack
printf("Binary equivalent: ");
for (int i = top; i >= 0; i--) {
printf("%d", binary[i]); // Pop and print each binary digit
}
printf("\n");
}
int main() {
int decimal;
// Prompt the user for input
printf("Enter a decimal number: ");
scanf("%d", &decimal);
// Call the function to convert decimal to binary
decimalToBinary(decimal);
return 0;
}
Output:
Enter a decimal number: 10
Binary equivalent: 1010
=== Code Execution Successful ===
How the code works:
- Input: The user enters a decimal number.
- Function Call: The decimalToBinary function is invoked with the decimal number as an argument.
- Inside Function:
- The function initialises a stack (array) to store binary digits, with the top variable tracking the stack's current position.
- A for loop is used to convert the decimal number to binary. Each division by 2 gives a remainder, which is pushed onto the stack.
- Reverse Output:
- Once all binary digits are stored in the stack, the program "pops" and prints each digit starting from the top of the stack.
- This ensures that the binary number is displayed in the correct order.
C Program to Convert Decimal to Binary Number Using Bitwise Operator
Algorithm:
1. Initialize Variables:
- Declare an integer variable to store the decimal number and a variable to store the binary digits.
2. Input Decimal Number:
- Prompt the user to input a decimal number.
3. Bitwise Operation Loop:
- Start a while loop that runs as long as the decimal number is greater than 0.
- Inside the loop:
- Use the bitwise AND operator (&) to get the least significant bit (binary digit) by performing decimal & 1.
- Shift the decimal number one bit to the right using the bitwise right shift operator (>>) to prepare for the next iteration.
- Store the result in the binary output (can be printed directly or stored in a variable).
4. Output the Binary Number:
- The binary digits are printed in reverse order, as the least significant bit is calculated first. You can reverse the output or store it for correct printing.
5. End the Program:
- The program ends once the binary representation is printed.
Now let’s look at decimal to binary C code using the bitwise operator:
#include <stdio.h>
// Function to convert decimal to binary using bitwise operator
void decimalToBinary(int decimal) {
int i;
int isLeadingZero = 1; // Flag to skip leading zeros
// Check if the decimal number is 0
if (decimal == 0) {
printf("Binary equivalent: 0\n");
return;
}
printf("Binary equivalent: ");
// Iterate through each bit using the bitwise right shift
for (i = 31; i >= 0; i--) {
int bit = (decimal >> i) & 1; // Right shift and mask to get the bit at position i
// Skip leading zeros
if (bit == 1) {
isLeadingZero = 0; // Once we find the first 1, stop skipping zeros
}
if (!isLeadingZero) {
printf("%d", bit); // Print the bit if it's not a leading zero
}
}
printf("\n");
}
int main() {
int decimal;
// Prompt the user for input
printf("Enter a decimal number: ");
scanf("%d", &decimal);
// Call the function to convert decimal to binary
decimalToBinary(decimal);
return 0;
}
Output:
Enter a decimal number: 15
Binary equivalent: 1111
=== Code Execution Successful ===
How the code works:
- Input: The user enters a decimal number.
- Function Call: The decimalToBinary function is invoked with the decimal number as an argument.
- Bitwise Conversion:
- A for loop iterates through each of the 32 bits of the decimal number, starting from the most significant bit.
- The >> (right shift) operator shifts the bits, and the & 1 operation checks if the bit is 1 or 0.
- Leading zeros are skipped using the isLeadingZero flag.
- Output the Binary Number:
- The binary digits are printed, starting from the most significant bit, without leading zeros, to give the correct binary representation of the decimal number.
C Program to Convert Decimal to Binary Number Without Using Array
Algorithm:
1. Initialize Variables:
- Declare an integer variable to store the decimal number.
- Declare a variable to store the remainder (binary digit).
2. Input Decimal Number:
- Prompt the user to input a decimal number.
3. Conversion Process:
- Start a while loop that continues as long as the decimal number is greater than 0.
- Inside the loop:
- Calculate the remainder by dividing the decimal number by 2 (using modulus %).
- Print the remainder (binary digit).
- Update the decimal number by dividing it by 2 (using integer division).
4. Output the Binary Number:
- The binary digits are printed in reverse order since the least significant bit is printed first.
- To correct the order, you can print the digits from last to first (in reverse) or use a different method to store and print.
5. End the Program:
- The program ends after printing the binary digits.
Now let’s convert binary to decimal in C without using an array:
#include <stdio.h>
// Function to convert decimal to binary without using an array
void decimalToBinary(int decimal) {
// Handle the case for zero
if (decimal == 0) {
printf("Binary equivalent: 0\n");
return;
}
printf("Binary equivalent: ");
int isLeadingZero = 1; // Flag to skip leading zeros
// Iterate through each bit using the bitwise right shift
for (int i = 31; i >= 0; i--) {
int bit = (decimal >> i) & 1; // Right shift and mask to get the bit at position i
// Skip leading zeros
if (bit == 1 || !isLeadingZero) {
printf("%d", bit); // Print bit and stop skipping leading zeros
isLeadingZero = 0; // After printing the first 1, stop skipping
}
}
printf("\n");
}
int main() {
int decimal;
// Prompt the user for input
printf("Enter a decimal number: ");
scanf("%d", &decimal);
// Call the function to convert decimal to binary
decimalToBinary(decimal);
return 0;
}
Output:
Enter a decimal number: 20
Binary equivalent: 10100
=== Code Execution Successful ===
How the code works:
- Input: The user enters a decimal number.
- Bitwise Conversion:
- The program uses a for loop to iterate through each bit, starting from the most significant bit (leftmost).
- The >> (right shift) operator shifts the bits of the number to the right, and the & 1 operation checks if the current bit is 1 or 0.
- Skip Leading Zeros:
- The variable isLeadingZero helps skip leading zeros in the binary output. The first 1 encountered stops the skipping, and the rest of the bits are printed.
- Output:
- The binary digits are printed, ensuring no leading zeros and giving the correct binary representation of the decimal number.
Conclusion
This exercise of converting decimals to binary in different ways is crucial for students to grasp the fundamentals of coding. By implementing various approaches, such as using loops, functions, bitwise operators, and arrays, students learn to think in different ways and choose the most efficient solution. It strengthens their understanding of data manipulation, logical operations, and problem-solving. Mastering these concepts lays a strong foundation for more advanced topics in programming, enhances their coding skills, and prepares them for real-world programming challenges. If you wish to learn more and build a strong foundation that prepares you for a job, enroll on the CCBP Academy 4.0 program.
Boost Your Placement Chances by Learning Industry-Relevant Skills While in College!
Explore ProgramFrequently Asked Questions
1. What is the purpose of converting decimal to binary?
Decimal to binary conversion is needed for computer science as these machines use binary (base-2) to process and store data. Understanding this conversion helps you to learn how data is represented and manipulated at the machine level.
2. What is the division 2 conversion method?
The division by 2 methods for conversion means calculating the division of a decimal number with 2, and each digit is noted in terms of the remainder. Taking the division of each digit in a definite number from a unit digital number gives a remainder, which is 0 or 1, which forms a binary digit. The binary number is then obtained by reading the remainder from the last towards the first that was obtained during the division exercise. This process is done until the quotient is zero, and all the remainder offered in binary form signify the Decimal value of a number.
3. What about negative decimal numbers in conversion?
For negative numbers, you can use what is known as a two-s complement to represent them in binary position. This pertains to converting the bits of the positive equivalent and making its complement by adding one more.
4. How does using a function improve decimal to binary program in C?
Using functions makes the code modular and easier to manage. It helps break down the problem into smaller, manageable parts, improving code readability and maintainability.
5. Why are bitwise operators used in decimal to binary programs?
Bitwise operators allow direct manipulation of individual bits in a number. It is ideal for tasks like converting decimals to binary ones.