# Thread: Binary to Decimal help...

1. ## Binary to Decimal help...

i cant figure out how i should write a c program regarding this problem...

when i enter a binary number,say 101101, the result would be the decimal equivalent of 45...

it goes like this,

1 0 1 1 0 1 equals
32 16 8 4 2 1

so,form right to left, it goes like 1,2,4,8,16,32,64,128,256,512,1024...so on...(like IP addressing,VLSM...)
it will add only on values of 1 and not 0...

counting is from right to left,but it wont start until 1 is the rightmost...

using if and then or loops is not allowed...only arithmetic operators...

2. just write the program using loops, then remove the loop, and copy the inside of the loop into your code over and over

edit: if your just learning how to program, im sorry, but you have a terrible teacher/lecturer/tutor/textbook

3. Originally Posted by anarcho
using if and then or loops is not allowed...only arithmetic operators...
Without using at least a while() loop, you can only do this if the number is of fixed length, and then it will just be cut and paste some almost identical code over and over. Here's a clue: put the binary number into a char string:
Code:
`char num[]="101101";`
So the fixed length is 6. If you want to work right to left (aka "big endian"), start with num[5]:
Code:
```int total = 0, add = 1;
if (num[5] == '1') total += add;
if (num[4] == '1') total += add;
[...etc]```
If you can't even use "if", those lines could be:
Code:
`total += add*(num[5] - '0');`
Notice, '0' (which '0' == 48) not 0. For an understanding of that read up on the ASCII table:
http://www.idevelopment.info/data/Pr...ii_table.shtml
http://en.wikipedia.org/wiki/ASCII

4. Is this a recursion problem you are supposed to do? Cause, without using loops, that is about the only way to do it.

5. So why can't you go from left to right? Might be easier IMO.

 as noted recursion is the only alternative if loops are a no-no.

6. Originally Posted by itCbitC
 as noted recursion is the only alternative if loops are a no-no.
No, if this is to deal with a fixed number of bits (in the example, 6), you don't need either, but you will end up with some "worst practice" long noodle style code exemplifying unnecessary duplication.

7. Would it really be possible to do with recursion without "if" ?

8. Assuming the instructor really wants them to use recursion like Kennedy suggested, then the instructor is an absolute retard. o_O

9. Yes. You use return values and tertiaries.

10. Yes but using tertiaries is equivalent to using if statements, what I meant of course is, without any way of testing a condition.

11. Methinks! MK27 has a good point because w/o a fixed no. of input characters this won't be possible w/o using ifs or loops.
And agree with Susonics too, because even with the use of recursion the EOF condition has to be tested for the input.