# Thread: Help with converting to base 10 program

1. Member
Join Date
Mar 2012
Posts
24
Rep Power
0

## Help with converting to base 10 program

I am trying to convert these into a base 10
1010
1000
1001
0101
0110
1100
1110
1111
11111
111111
1110101
10101010101
1010101010110
111111111111111111
Here is my code
Java Code:
```	import java.io.*;
import java.util.*;
public class prog606 {
public static void main (String [] args)throws IOException
{
Scanner file = new Scanner(new File("prog606.dat"));
int size = file.nextInt();

while(file.hasNextInt())
{
int num = file.nextInt();
if (num<0) num=-num; // maybe you'd like to support negatives

while (num>0) {
num=num/10;
}
int bobby = getbase(digits);
System.out.println("base is "+bobby);
}
}
public static int getbase(List<Integer> x)
{
int base = 0;
int sum = 0;
Collections.reverse(x);
for(int i = 0; i<x.size();i++){
int jay = x.get(i);
for(int k = 0;k<x.size();k++){
sum = jay*(2^k);
base+=sum;
}
}
return base;
}
}```
Here is my output:
Java Code:
```base is 12
base is 6
base is 12
base is 10
base is 10
base is 12
base is 18
base is 24
base is 60
base is 114
base is 115```
The bases are supposed to be

1010 == 10

1000 == 8

1001 == 9

0101 == 5

0110 == 6

1100 == 12

1110 == 14

1111 == 15

11111 == 31

111111 == 63

1110101 == 117

10101010101 == 1365

1010101010110 == 5462

111111111111111111 == 262143

I can't find what I'm doing wrong

2. AN21XX
Join Date
Mar 2012
Location
Munich
Posts
298
Rep Power
9

## Re: Help with converting to base 10 program

Just some suggestions without knowing the exact reason right now:
- negative numbers (EDIT: _binary_ numbers) are usually not signed by a minus. That means your input cannot be negative.
- why don't you just use the input string and go through its characters ('0' and '1' are much more easily to be identified and debugged)
- what do you need that inner sum loop for? You may use the leftshift operator "<<" like "jay << k" which is "jay" leftshift by k bits.
- you could as well use the "BigInteger" class for your conversion - as in BigInteger("100101000111111110000", 2);
Last edited by Sierra; 04-23-2012 at 01:24 PM.

3. ## Re: Help with converting to base 10 program

Try debugging the code by printing out the values of the variables as the code executes to see what it is doing.

#### Posting Permissions

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