Convert Binary To Decimal In C | 4 Ways Explained (+Code Examples)
Table of content:
- What Is A Binary Number?
- What Is A Decimal Number?
- Algorithm To Convert Binary To Decimal In C
- Convert Binary To Decimal In C Using While loop
- Convert Binary To Decimal In C Using For Loop
- Convert Binary To Decimal In C Using Function
- Convert Binary To Decimal In C Using Arrays
- Complexity Comparison For Programs To Convert Binary To Decimal In C
- Why Convert Numbers From Binary To Decimals In C?
- Conclusion
- Frequently Asked Questions
Binary and decimal are two fundamental number systems that are an integral part of operations in computer science and mathematics. Binary represents numbers using only two digits (0 and 1), and decimal uses ten digits (0 through 9). Converting binary numbers to their decimal equivalents is a common task in programming, particularly in applications involving bitwise operations, digital electronics, and data encoding. In this article, we will discuss the various methods in which we can convert binary to decimal in C programming.
We will discuss the conversion approaches from binary to decimal in C, their implementation, efficiency, pros/cons, and best practices. Whether you're a beginner learning C programming or an experienced developer seeking efficient conversion techniques, this article provides insights and strategies to handle binary-to-decimal conversion tasks in C effectively.
What Is A Binary Number?
A binary numeral is a numerical construct that symbolises data or information held within a computer. It is formed by amalgamating bits of 0s and 1s. This numeral system is alternatively referred to as the base-2 system due to its reliance on two fundamental components: 0 and 1.
For instance, the binary number 1001 translates to the decimal number 9, while 1010 corresponds to 10 in the decimal system. The sequences of 0s and 1s convey meaningful values when decoded correctly. Computers can store and manipulate data, do calculations, and make choices using these binary representations in an exhilarating dance of on-off signals.
Example of binary to decimal conversion:
Binary Number 101: In this example, we have a binary number "101." Each digit in the binary number represents a power of 2. Starting from the right, the positions represent 2^0, 2^1, and 2^2.
- The rightmost digit (1) represents 2^0, which is 1.
- The middle digit (0) represents 2^1, which is 0.
- The leftmost digit (1) represents 2^2, which is 4.
What Is A Decimal Number?
A numerical value that is expressed using the base-10 number system is referred to as a decimal number. It uses 10 different symbols, including 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9, which collectively form the basis of our number language. Let's take the number 456 as an example.
- In the decimal system, the rightmost digit (6) represents the ones place, the middle digit (5) represents the tens place, and the leftmost digit (4) represents the hundreds place.
- So, 456 means you have 4 sets of 100, 5 sets of 10, and 6 individual units, making a total of 456.
Algorithm To Convert Binary To Decimal In C
The process of converting a binary to decimal in C language involves multiplying each digit of the binary number by its corresponding power of 2 and then adding up the results. Here's a step-by-step description of the basic algorithm to write and run a C program for converting binary to decimal:
- Initialize variables: Declare variables to store the binary number and the corresponding decimal number.
- Read input: When taking input from users, read the binary number and store it in the respective variable using the address-of/ reference operator (&).
- Iterate through the binary number: Use any iterative construct to iterate through the bits of the binary number. Start from the rightmost bit (least significant bit) and move towards the leftmost bit (most significant bit).
- Calculate decimal equivalent: For each bit in the binary number, multiply the bit by 2^i, where is the position of the bit (0-indexed), and add the result to the decimal number.
- Display result: Print the program output, i.e. the decimal equivalent of the binary form.
Pseudocode for Program to Convert Binary to Decimal in C:
// Initialize variables
decimalNumber = 0
// Read input
Read binaryNumber from user or another source// Iterate through the binary number
Set i = 0
while binaryNumber is not zero:
remainder = binaryNumber % 10
binaryNumber = binaryNumber / 10
decimalNumber = decimalNumber + remainder * 2^i
Increment i by 1// Display result
Print decimalNumber
Now that we know the basic logic behind a program to convert binary to decimal in C programming language, let's look at the various techniques and control statements/ constructs we can use to write the programs.
Convert Binary To Decimal In C Using While loop
We can carry out the conversion from binary to decimal in C programs using the while loop. The approach is pretty straightforward, where the while loop extracts each digit of the binary number one by one, calculates its contribution to the decimal equivalent, and updates the result accordingly. The simple C program example below showcases how to implement this method.
Code Example:
Output:
Enter a binary number: 101010
Decimal equivalent: 42
Explanation:
In the sample C code, we include the essential header file <stdio.h> for input-output operations.
- We then initiate the main() function, the entry point for the program's execution.
- Inside main(), we declare a variable binaryNumber to store the user's input binary number.
- Next, we prompt the user to enter a value for the variable using printf(), read it using scanf() and store it in the respective variable using the reference/ address-of operator (&).
- We then declare two integer data type variables, decimalEquivalent and base, and assign them the values 0 and 1, respectively.
- Following this, we define a while loop (conversion loop) which continues implementing until the binaryNumber becomes zero.
- Inside the loop, we extract the rightmost binary digit by taking the modulo (%) of binaryNumber with 10. (Using modulo arithmetic operator)
- This extracted binary digit is then multiplied by the current base and added to decimalEquivalent. (Using compound addition assignment operator)
- After that, we update the value of the base variable by multiplying it by 2 to prepare for the next position in the binary number.
- Then, we remove the rightmost digit from binaryNumber by dividing it by 10.
- Once the loop completes, the decimalEquivalent variable will contain the binary to decimal conversion value.
- We use the printf() function to display the value to the console, where the %d format specifier is the placeholder for the integer value, and the newline escape sequence shifts the cursor to the new line.
- Finally, the main() function terminates with return 0 statement indicating successful execution.
Time Complexity: The code has a time complexity of O(n), where n is the number of digits in the binary input.
Space Complexity: The code has a space complexity of O(1), meaning it uses a constant amount of memory regardless of the input size.
Convert Binary To Decimal In C Using For Loop
Using the for loop to convert a number from binary to decimal in C programs is another efficient and concise approach that makes use of iteration. We can use this looping construct to iterate through each bit of the binary number to calculate its decimal equivalent by multiplying each binary digit with the appropriate power of 2 and summing them up. Look at the sample C program below to understand how to implement this approach.
Code Example:
Output:
Please enter a binary number: 1101
Binary number entered: 1101
Equivalent decimal number: 13
Explanation:
In the C code sample-
- We initialize three local variables, count (for iteration), binaryInput, and decimalOutput to the value 0 in a single line using the comma operator. And also declare a fourth integer variable remainder without initialization.
- Then, we prompt the user to enter a binary number using printf() and use scanf() with address-of (&) to read the user input and store the value in the binaryInput variable.
- We then assign the value of the binaryInput variable to the count variable.
- Next, we create a for loop for conversion such that it iterates until the count variable becomes zero.
- Inside the loop, we obtain the rightmost position/ digit of the count variable using the modulo operator (%) and store it in remainder.
- We then remove the rightmost digit from the count by dividing it by 10.
- Then, we update the value of the decimalOutput variable by adding the product of the remainder and 2 raised to the power of position (representing the position of the digit in the binary number).
- We use the built-in function pow(), i.e., the power function, to calculate 2 raised to the power given by position.
- The loop begins at position set to 0 and continues till the time the count variable is not equal to 1 (checked using not equal to relational operator). After every iteration, the value of the position variable is incremented by 1.
- Once the loop completes execution, the decimalOutput variable will contain the decimal equivalent to the initial binary value.
- Lastly, we use a set of printf() statements to display the original binary input and the resulting decimal output using printf.
- In this example, we convert the binary number 1101 to decimal which is 13, as shown in the output console.
Time Complexity: The code has a time complexity of O(n), where n is the number of digits in the binary input.
Space Complexity: The code has a space complexity of O(1), indicating constant memory usage regardless of the input size.
Convert Binary To Decimal In C Using Function
Functions are building blocks of programs that enclose a segment of code, which can be called upon over and over again with different inputs/ parameters. it is possible to define a custom function to convert numbers from binary to decimal in C programs with ease. You can use any suitable technique in the function to get this done. In the example C program below, we have defined a function in conjunction with a while loop to convert binary integers into their decimal equivalents.
Code Example:
Output:
Enter a binary number: 10101
Binary number entered: 10101
Equivalent decimal number: 21
Explanation:
In the example C code-
- We define a function binaryToDecimal(), which takes an integer representing a binary number as input and returns its decimal equivalent.
- In the function, we first initialize integer variable decimalEquivalent to 0 and base to 1.
- Then, we employ a while loop that continues iterating until the value of binaryNumber variable becomes zero.
- Inside the loop, we extract the rightmost position/ digit of the binary number by taking its remainder from division by 10 and storing it in a variable called binaryDigit.
- We then update the value of decimalEquivalent variable by adding the product of the binaryDigit variable with the base variable.
- After that, we update the value of base variable by doubling it before the next iteration to consider the next position/ digit in the binary number.
- The loop continues these iterations of dividing the binary number by 10 to remove the rightmost digit.
- It terminates once the input variable binaryNumber becomes zero, and the function returns the decimalEquivalent. This variable holds the decimal equivalent of the input binary number.
- In the main() function, we declare an integer data type variable binaryInput and prompt the user to provide a value for the same.
- After that, we call the binaryToDecimal() function with binaryInput as an argument, and the outcome is stored in the decimalOutput variable.
- Lastly, we use two printf() statements to display the input binary number and its equivalent decimal number to the program output console.
- In this example, we convert the 10101 binary to decimal number 21, as shown in the console.
Time Complexity: The code's time complexity is O(n), where n is the number of digits in the binary input.
Space Complexity: The code's space complexity is O(1), indicating constant memory usage regardless of the input size.
Check out this amazing course to become the best version of the C programmer you can be.
Convert Binary To Decimal In C Using Arrays
In this approach to converting binary to decimal in C, we will make use of an array by representing the binary digits as its elements. This makes for a well-defined structured approach to convert numbers from binary to decimal. Under this approach, you must store the digits of the binary number in an integer array and then calculate the decimal equivalent. Look at the C program example below to see how this can be done.
Code Example:
Output:
Enter a binary number: 1010
Binary number entered: 0
Equivalent decimal number: 10
Explanation:
In the C code example-
- We begin by defining a function binaryToDecimal(), which takes an array of binary digits and its size as input and returns the decimal equivalent of the binary number.
- In the function, we first initialize an integer variable decimalEquivalent to 0. This will be used to store the decimal equivalent of the binary number.
- Next, we use a for loop to iterate over each digit of an array from right to left.
- In every iteration, we first assign the array element at position i to the binaryDigit variable.
- Then, we calculate the decimal equivalent of the digit by multiplying it by 2 raised to the power of its position, using the pow() function.
- The result is stored in the decimalEquivalent variable and the value of loop variable i is decremented by 1 before the next iteration.
- The loop continues iterating till i>=0, and the function returns the decimalEquivalent once the loop completes execution.
- In the main() function, we declare an integer variable binaryInput and prompt the user to enter a binary number to store it.
- We then assign the value of binaryInput variable to a new temporary variable called tempBinary, and initialize another variable numDigits, with the value 0.
- As mentioned in the code comment, we use a while loop to calculate the number of digits in the binary number. In the loop, we divide the tempBinary variable by 10 until the quotient becomes zero.
- For every iteration, we increment the value of the numDigits variable. After the loop completes iterations, this variable will give the number of digits in the input binary number.
- After determining the number of digits, we initialize an array binaryArray to store the individual binary digits. The size of the array is the value of the numDigits variable.
- Following this, we use a for loop to iterate through this array and calculate the decimal equivalent of the binary number.
- In every iteration, we extract each digit of the binary number and store it in the array binaryArray.
- Next, we call the binaryToDecimal() function, passing the array of binary digits and its size as arguments.
- The function calculates and returns the decimal equivalent of the input binary number stored in the decimalOutput variable.
- Lastly, we use the printf() function twice to print the input binary number and its decimal representation.
Time Complexity: The code's time complexity is approximately O(log N), where N is the binary input.
Space Complexity: The code's space complexity is also approximately O(log N).
Complexity Comparison For Programs To Convert Binary To Decimal In C
Let's compare the time and space complexity of the methods discussed for converting a binary to decimal in C, as shown in the table below.
Method |
Time Complexity |
Space Complexity |
While Loop Approach |
O(n) |
O(1) |
For Loop Approach |
O(n) |
O(1) |
Convert Binary To Decimal Using Function |
O(n) |
O(1) |
Convert Binary To Decimal In C using array and function |
O(log n) |
O(log n) |
Why Convert Numbers From Binary To Decimals In C?
Converting numbers from binary to decimals in programming, including the C programming language, is a common task when working with binary data or performing bitwise operations. As mentioned before, binary numbers are represented using only two digits, 0 and 1, whereas decimal numbers are represented using ten digits, 0 to 9. There are several situations when converting binary to decimal in C is beneficial, including:
- Human Readability: Binary numbers can be challenging for humans to read and understand, especially when dealing with longer sequences of digits. Converting them to decimals makes them more intuitive and easier to interpret.
- Display and Output: When binary data needs to be displayed to users or printed in a human-readable format, converting it to decimal allows for a clearer presentation.
- Arithmetic Operations: Converting binary numbers to decimal is often necessary when performing arithmetic operations with binary values. For instance, you might need to add, subtract, or multiply binary numbers, and these operations are typically easier to perform in decimal form.
- Debugging and Testing: When working with binary data, debugging can be challenging due to the abstract nature of binary representations. Debugging can be facilitated by converting binary to decimal since it makes it simpler to compare and visualize numeric values.
Looking for mentors? Find the perfect mentor for select experienced coding & software experts here.
Conclusion
In conclusion, there are several ways of converting numbers from binary to decimal in C programming. These include using loops (while and for), functions, arrays and mathematical operations. Each of these comes with its own trade-offs in terms of simplicity, efficiency, and space usage. Programmers can choose the approach that best suits their specific requirements and preferences. Each method also has its own time and space complexities, which should be considered when selecting the most appropriate solution for a given scenario.
Understanding the principles behind the conversion of numbers from binary to decimal in C and the available implementation techniques empowers programmers to efficiently handle binary data and perform numerical computations in their C programs.
Also Read: 100+ Top C Interview Questions With Answers (2024)
Frequently Asked Questions
Q. How to write binary numbers in C?
In C, you can represent binary numbers using a prefix of 0b followed by the binary digits. For example, 0b1010 represents the binary number 1010. Alternatively, you can use integer literals and specify the base as 2 using the 0b prefix. For instance, int binaryNumber = 0b1010; assigns the binary number 1010 to the variable binaryNumber. Binary numbers can also be stored in character arrays or strings, where each character represents a binary digit ('0' or '1').
Q. How to convert hex to decimal in C?
You can use the standard C library functions to convert a hexadecimal (hex) number to its decimal equivalent in C. Here's the general process:
- Input the Hexadecimal Number: Prompt the user to input the hexadecimal number using scanf.
- Convert Hex to Decimal: Use the strtol built-in function from the <stdlib.h> library to convert the hexadecimal input to a decimal integer. The function name/ identifier strtol is short for "string to long" and is capable of handling different number bases.
- Output the Decimal Equivalent: Display the decimal equivalent using printf.
Look at the C program sample below to understand how to implement this logic in actual code.
Code Example:
Output:
Enter a hexadecimal number: 1A
Decimal equivalent: 26
Explanation:
In the example C code, we prompt the user to input a hexadecimal number, read it as a string, and then convert it to its decimal equivalent using the strtol function from the <stdlib.h> library. We then store the decimal equivalent in a long variable and print it out using the printf() function. The program assumes a reasonable length for the hexadecimal input, represented by the hexInput array. Finally, it returns 0 to indicate successful execution.
Q. What is the decimal representation of binary 1111 1101?
The binary number 1111 1101 represents a sequence of eight binary digits (bits), where each bit is either a 0 or a 1. To convert this binary number into its decimal equivalent, we need to interpret each bit's positional value in the context of the decimal system. So, The decimal representation of the binary number 1111 1101 is 253.
Let's break down the binary number 1111 1101:
- 1 * 2^7 + 1 * 2^6 + 1 * 2^5 + 1 * 2^4 + 1 * 2^3 + 1 * 2^2 + 0 * 2^1 + 1 * 2^0
- 128 + 64 + 32 + 16 + 8 + 4 + 0 + 1
- 128 + 64 + 32 + 16 + 8 + 4 + 1 = 253
Alternatively, you can convert the number from binary to decimal in C language, i.e., by writing and running a C program.
Q. Can I convert large binary numbers to decimal in C?
Yes, you can convert large numbers from binary to decimal in C as long as you use data types that can handle large values. In C, you can use data types like unsigned long long or unsigned __int128 to store and manipulate large integers. Additionally, you can use libraries like GMP (GNU Multiple Precision Arithmetic Library) for arbitrary-precision arithmetic, which allows you to handle extremely large binary numbers with precision. However, keep in mind that the performance of operations on large numbers may vary depending on the implementation and hardware capabilities.
Q. What's the most efficient method for converting binary to decimal in C?
The most efficient method for converting binary to decimal in C often involves direct mathematical calculations rather than using loops or arrays.
- One approach is to iterate through each binary digit, starting from the rightmost digit, and calculate its contribution to the decimal equivalent using powers of 2.
- By multiplying each binary digit by the corresponding power of 2 and summing them up, you can efficiently compute the decimal equivalent in a single pass through the binary number.
- This method minimizes the number of iterations and memory usage, making it efficient for converting numbers from binary to decimal in C.
Here are a few more topics you will love reading on:
- Conditional/ If-Else Statements In C | The Ultimate Guide
- Compilation In C | Detail Explanation Using Diagrams & Examples
- Ternary (Conditional) Operator In C Explained With Code Examples
- Type Casting In C | Cast Functions, Types & More (+Code Examples)
- Understanding Constant In C: How To Define, Syntax, and Types
Login to continue reading
And access exclusive content, personalized recommendations, and career-boosting opportunities.
Comments
Add comment