# Base Changing - Is there an easier method?

• October 2nd, 2011, 05:42 PM
Staticity
Base Changing - Is there an easier method?
So, as my first attempt to make a method that changes a base 10 number into another Base.. I came up with this:
Code :

``` public StringBuffer toBaseSixteen(long x){ boolean solving = true; String s = ""; long remain = 0; int i = 16; String [] list = {"A", "B", "C", "D", "E", "F"};   while(solving){ remain = x % i; if(remain > 9) s += list[(int) (remain-10)];   if(remain < 9) s += remain + "";   x /= i; new StringBuffer(s).reverse(); if(x<1){ solving = false; } } return new StringBuffer(s).reverse(); }```

Has anyone come up with a faster method? If so, could you point me in your direction of thought.. Or maybe even comment with your method?
• October 2nd, 2011, 05:48 PM
Sean4u
Re: Base Changing - Is there an easier method?
Have you seen the methods in java.lang.Integer that do this? Integer.parseInt(String, int) and Integer.toString(int, int)
• October 2nd, 2011, 05:56 PM
Staticity
Re: Base Changing - Is there an easier method?
Yes, I have! :) I just prefer to create these methods for practice, rather than use Java's library.
• October 2nd, 2011, 06:25 PM
Sean4u
Re: Base Changing - Is there an easier method?
'toBaseSixteen' has a trivial solution because you're not converting 'a decimal number', but an integer that's represented by binary bits. Base 2 to Base 2^N can be done by taking the N least significant bits, converting them to a base-N digit, and shifting the original number right N places.

If you want to make your own generic base-changing code, you should use the template from Integer and implement parseInt(String, int) and toString(int, int), so that you can 'eat your own dog food' (convert an integer to a String, convert that String back to the original integer) to test that it works.