# Thread: Binary to Decimal conversion

1. Join Date
Dec 2011
Posts
7
Rep Power
0

## Binary to Decimal conversion

Hello, I am extremely new to Java programming and I need write a program to convert binary numbers to decimal numbers. The input is a string of zeros and ones.
(1001010101011010111001011101010101010101)

All I know is I need to, use a loop to read (charAt()) each digit (0/1 char) in the input string, scanning from right to left, then I need to use the loop to build the required powers of 2. I need to use a conditional statement to deal with 0 and 1 separately, Then I need to Debug using simple input, e.g. 1, 10, 101, and print intermediate values in the loop.

It would be great if someone could help me out with this code as I am very new to this topic

2. ## Re: Binary to Decimal conversion

Can you do it with pencil and paper, with a binary number, say, 1011?

kind regards,

Jos

3. Join Date
Dec 2011
Posts
7
Rep Power
0

## Re: Binary to Decimal conversion

8 4 2 1
1 0 1 1

8+2+1= 11

that is fine, just how to do it with a program please if anyone could help me with that?

4. ## Re: Binary to Decimal conversion

Good; have a look at the top row: it can also be written as, 2*2*2*1, 2*2*1, 2*1, 1; this implies that if you look at the leftmost digit in your binary number (0 or 1), the answer is 0 or 1 too. If more digits follow, you have to multiply your answer by two; in (pseudo) code it look like this:

Java Code:
```result= 0;
for (int i= 0; i < digit.length(); i++) { // walk over all digits
result*= 2; // prepare for another digit, see above
result+= // digit at location i
}```
kind regards,

Jos

5. Join Date
Dec 2011
Posts
7
Rep Power
0

## Re: Binary to Decimal conversion

Thank you very much for your help Jos, as I now understand. I hope to see you furthermore as I continue to learn java coding. (y)

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•