Hi,
I was wondering is anyone could tell me how or give me pointers on how to convert the base of a number to another base. For example 2010 base 3 to base 4. I am stumped and I would appreciate any help I could get.
crackers8838
- 3 Contributors
- forum3 Replies
- 4 Views
- 11 Years Discussion Span
- comment Latest Post by javabru
TylerSBreton 13
I dont think java provides any convienient way of doing this, you'll probably need to do it out longhand with loops and the % operator.
crackers8838
Ok, thanks. That is what I thought. I was hoping there was an easier way to do it.
javabru
Hi,
I was wondering is anyone could tell me how or give me pointers on how to convert the base of a number to another base. For example 2010 base 3 to base 4. I am stumped and I would appreciate any help I could get.
I'm no expert, but you can do something like this:
public class Base3ToBase4 {
public static void main(String[] args) {
Base3ToBase4 tester = new Base3ToBase4();
tester.test();
}
public void test() {
long num3 = Long.parseLong("2010", 3);
prt("num3 has a value of " + num3);
String num3StrAsBase3 = Long.toString(num3, 3);
prt("num3 as a String in Base 3 = " + num3StrAsBase3);
String num3StrAsBase10 = Long.toString(num3, 10);
prt("num3 as a String in Base 10 = " + num3StrAsBase10);
String num3StrAsBase4 = Long.toString(num3, 4);
prt("num3 as a String in Base 4 = " + num3StrAsBase4);
prt(" *----------*");
long num4 = Long.parseLong(num3StrAsBase4, 4);
prt("num4 has a value of " + num4);
String num4StrAsBase10 = Long.toString(num3, 10);
prt("num4 as a String in Base 10 = " + num4StrAsBase10);
String num4StrAsBase4 = Long.toString(num4, 4);
prt("num4 as a String in Base 4 = " + num4StrAsBase4);
}
private void prt(String str) {
System.out.println(str);
}
}
The thing is, that the Long class keeps the same number, no matter what base it is in. Using the Long.toString(long num, int radix) method you can look at a String representation of the number in the base of your choice, and using Long.parseLong(String num, int radix) you can turn any String that validly represents a number in the associated base, into a long.
- Mike Bruton