Results 1 to 3 of 3
 04232012, 07:23 AM #1Member
 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 List<Integer> digits = new LinkedList<Integer>(); while (num>0) { digits.add(0, num%10); 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; } }
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
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
 04232012, 12:33 PM #2AN21XX
 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; 04232012 at 01:24 PM.
 04232012, 01:20 PM #3
Similar Threads

Converting Number to Base 8
By nighteagle2 in forum New To JavaReplies: 9Last Post: 02172012, 02:38 AM 
converting a given positive integer m to a positional number system in base n
By Renxx in forum New To JavaReplies: 2Last Post: 11272011, 05:11 PM 
Converting Program from ArrayLists to Arrays
By JavaGuy in forum New To JavaReplies: 3Last Post: 01262011, 09:02 AM 
Converting an array program to ArrayList
By Adomini in forum New To JavaReplies: 4Last Post: 10132010, 07:22 PM 
A Number Converting Program!
By WastedxYears in forum New To JavaReplies: 2Last Post: 01092010, 12:47 AM
Bookmarks