Input an integer containing only 0’s and 1’s( ie. “binary” integer) and print its decimal equivalent. {hint: use the remainder and division operators to pick off the binary numbers digits one at a time from right to left. Just as in the decimal number system, in which the right most digit has a positional value of 1, and the next digit has a positional value of 10, then 100, then 1000, and so on, in the binary number system the rightmost digit has a positional value of 1, the next digit left has a positional value of 2, then 4, then 8, and so on. Thus the decimal number 234 can be interpreted as 4*1+3*10+2*100. The decimal equivalent of binary 1101 is 1*1+0*2+1*4+1*8 or 1+0+4+8 or 13.}

#include <stdio.h>
int bin;
int dec = 0;
scanf("%d",& bin);
int pos = 1;
while (bin) {
int digit = bin % 10;
dec += digit * pos;
bin /= 10;
pos *= 2;
}
printf("%d", dec);

Recommended Answers

All 6 Replies

Please use code tags.

Your code works fine for me. What's giving you trouble?

Use bin%2 bin/2

Use bin%2 bin/2, you have got binary numbers

Did you read the OP's post?

Your code works fine for me.

Perhaps you think you are a lot brighter than I, who took the time to actually compile and execute his code, after reading it over and finding no obvious flaw?

I'm sorry to be harsh...

what are code tags?

At the top of the forum there's an announcement post named "Please use BB Code and Inlinecode tags". It makes reading and copying code both easy and pleasant.

So, did you get your program to work?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.