The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

Base Conversion

I'm trying to write a program that inputs a number and a base and converts that number to a base. I have written the following which compiles, but doesn't seem to do the right thing :S Any help would be much appreciated

Re: Base Conversion

Yeah, returning n % b is just going to give the remainder after division by b. Useful for converting bases, but not enough.

Think about it like this. A way to get a number's base ten representation is to divide by powers of 10 and take the remainder after division by 10. This gives every digit. What do I mean? Consider the base ten representation of the number one thousand three hundred and twenty-four.

Dividing by 1 gives one thousand three hundred and twenty-four. The remainder after division of this is four. Therefore, the one's digit of the number is a 4.

Dividing by 10 gives one hundred thirty-two. The remainder after division by 10 is two, so the 10's digit is 2.

Dividing by 100 gives thirteen. The remainder after division by 10 is three, so the 100's digit is 3.

Dividing by 1000 gives 1. The remainder after division by 10 is 1, so the 1000's digit is 1.

Dividing by 10000 gives 0, and the algorithm stops at this stage. The representation you have constructed is the base ten representation of the number.

You might be thinking that it should work the same for hexadecimal, just use 16 instead of 10. This is correct. Just make sure you map digits greater than 9 to the corresponding letters of the alphabet, a, b, c, d, e, and f.

Re: Base Conversion

Integers in Java don't distinguish between bases (actually, none of the primitive data types do). In order to display the different representations you must use strings. To calculate what digit comes next:

1. modulate your current number by the base. That result is the digit to put at the beginning of the string (so, any digits calculated before go after this digit)
2. divide your current number by the base (you will get truncation, but that's ok because we want it here). This is your new current number.
3. repeat until your current number is 0.

Alternatively, you can use Java's Integer class to do this conversion for you.

Integer.toString(10,16); // the first number is the value, the second is the radix or base. I think this is limited from 2-16