Update
Because below answer at just works up to base 10 I've come up with following answer which works up to base 36:
private static final char[] CHARS = "0123456789abcdefghijklmnopqrstuvwxyz".toCharArray();
private static String convertIntToBase(int i, int base){
final StringBuilder builder = new StringBuilder();
do{
builder.append(CHARS[i % base]);
i /= base;
} while(i > 0);
return builder.reverse().toString();
}
The logic stays the same, but now by accessing the CHARS
array we can get up to base 36. Because we have now the whole alphabet and the numbers to create a new number in an other base.
Using this will now yield correct numbers for e.g. base 16:
convertIntToBase(255, 16);
Will return the correct hex value:
ff
Old
It's pretty simple, by division and using the remainder of the base and can be made also generic:
public String convertIntToBase(int i, int base){
final StringBuilder builder = new StringBuilder();
do {
builder.append(i % base);
i /= base;
} while(i > 0);
return builder.reverse().toString();
}
which then can be used like the following:
convertIntToBase(24, 3);
Which yields:
220
This works, as said with division and the remainder (modulo). With the sample number 24
we can go through the steps pretty easy. The iteration and calculation (i /= base) % base
can be split up into the following parts:
- divide
i
through the base
(i /= base
)
- split of the comma places (This is done automatically because division of integers in java are always floored)
- See what remainder stays by whole-dividing the
i
with the base
(i % base
)
- repeat if
i
is bigger than zero
So with the i = 24
and base = 3
it goes through the following steps:
- 24 % 3 = 0
- 24 / 3 = 8
- 8 % 3 = 2, because by whole-division we get that 3 is 8 times in 2, leaving 2
- 8 / 3 = 2
- 2 % 3 = 0
- 2 / 3 = 0
leaving you with the known result: 220