+ 1

Binary to decimal

Hey guys I want to write a program in C that receive a binary number and display it in decimal. But I don't know how can I do it!!! Can you help me?

25th Mar 2021, 6:01 PM
reza
reza - avatar
6 Answers
+ 3
@reza You can store your binary number as an array. And I'll try to explain in detail the theory you need. To convert binary to decimal, for every bit in your array you add the product of the: value of the bit (0 or 1) * significance of the bit. To calculate how significant a bit is you can start from the rightmost bit that has a significance (magnitude) of 1. Every next bit to the left is twice as significant than the previous (on the right). We do the calculations in base 10. Here's an example on 8 bits: 01001011 Let's write this number with more space in it magnitude 128 64 32 16 8 4 2 1 values 0 1 0 0 1 0 1 1 product 0 64 0 0 8 0 2 1 Add all the products: 0 + 64 + 0 + 0 + 8 + 0 + 2 + 1 = 75 (There are ways to do it faster if you want, like this: the leftmost bit multiply by 2, add the next bit, multiply by 2, ... etc. Do it the way you are most comfortable with and optimize it later.) Now maybe you can describe in your words how it's done and then try to write some code. Don't worry if it doesn't work the first time but try to do your best.
25th Mar 2021, 7:35 PM
Eddy M
+ 3
Eddy M my apologizes for that mistakes to you
26th Mar 2021, 4:50 AM
Atul [Inactive]
+ 1
Thank you Eddy M Atul Martin Taylor Thank you guys for your help
25th Mar 2021, 8:14 PM
reza
reza - avatar
+ 1
Atul, everybody makes mistakes. It's nice when we have an undo function and use it.
26th Mar 2021, 8:16 AM
Eddy M
+ 1
Thanks @Martin Taylor this is exactly what I want. thank you
26th Mar 2021, 5:03 PM
reza
reza - avatar
+ 1
@reza Please mark the answer Martin Taylor provided as correct. Somehow I understood you needed to know how it works and do the conversion by yourself.
27th Mar 2021, 7:03 AM
Eddy M