Write a c program to convert a binary number to its equivalent decimal number
Answers
int x = 5;
would declare and define an integer-valued variable x with a value of 101 in binary. But since this is a trivial case from a programmer’s point of view, I’m assuming you don’t mean this.
A more interesting question would be how to convert a character string that contains a decimal representation of a number into a binary value. A simple example would be any string literal with decimal values, such as “1234” (this time with the quotation marks). While it may be an interesting exercise to do this conversion manually (hint: you can perform arithmetic on ASCII values), luckily for us, the standard library contains functions to do just this kind of conversion. Look up the function “atoi”, for example (there are also others). You might also be interested in the “scanf” family of functions since they do the same thing.
Finally, when you want to output the value of the variable, you most often convert it back to decimal for human-readable output. This happens automatically if you use format specifiers such as “%d” with the printf function. But what if yo wanted to print the binary representation, as a character string? It turns out that there is no function in the standard library to do this.
So here we need to turn ourselves to doing things manually. What you need to know is to learn how to use the bitwise operators: left shift <<, right shift >>, bitwise and &, bitwise or |, bitwise xor ^, and the negation ~. By composition, these very simple operators can do magic. Read up on these operators, you’ll need to understand how they work, and if you ever want to keep working with C, you’ll need these very often.
You’ll need to understand that the integer-valued variable is a binary word of fixed length, such as 32 bits in the case of int on many architectures. In this case, you’ll need to learn how to extract the single bit that occupies the ith position of the word, using the aforementioned operators. You can do this by first shifting the word right by i bits, and then taking the bitwise and with the value 1. For example, to extract the 5th bit of the variable x, you’d write
(x >> 5) & 1
and once you’ve done that (and stored it in a suitable variable), you can print it out or store the value in a string. For the complete solution, you’ll just have to loop over the length of the variable (the number of bits in the word).
Explanation:
Please give me a point and please make me brainless I hope I can help you good day