# Thread: Binary to decimal c code

1. ## Binary to decimal c code

Hello experts i need a binary to decimal code .
i am interfacing an ADC toa controller to display the the corresponding voltage .
i googled got a lot of but i am facing some confusion please any body provide a sample with logic.
soryy i am not good in c programming

2. This seems like a highly unnecessary code but since you asked, to convert to decimal take the last digit and multiply by 2^0 ,the next digit by 2^1 etc until you reach the MSB then sum up the results. that's the logic. figure out a code.

3. Originally Posted by africanwizz
This seems like a highly unnecessary code but since you asked, to convert to decimal take the last digit and multiply by 2^0 ,the next digit by 2^1 etc until you reach the MSB then sum up the results. that's the logic. figure out a code.
I think that's the reverse of what thannara123 (probably) wants.

To convert a binary number (n) and display it in base10 (decimal) you want to repeatedly get the remainder of n divided by 10 (this is the right-most digit) and print it, divide n by 10, and continue until n is 0. It's the same principle as africanwizz suggested, of course. The thing to look out for is that if you implement exactly as I've described the digits will be printed in reverse.

The maximum number of digits in a (decimal) natural number is floor(log10(n)+1) so you can probably pre-allocate a destination array using malloc and that formula to to work out how much room you'll need, OR if you know the maximum that n can be you can just have an array with floor(log10(n)+1) + 1 elements in it. Store the digits in the array using the above method, terminate the array with \0 (to make it a string) and print it.

Another alternative is sprintf() but depending on what you're doing and how much memory you have, perhaps implementing your own "binary to decimal" function is preferable.

Edit: Yet another alternative is a recursive implementation of your "print" function.

Popular pages Recent additions