### Base/Base62 encoding with Java

Greetings!

Converting base 10 number to another base is a common mathematical operation. First of all, why do we need base62?
• Shorten a given URL
• Saving a file using timestamp
• Short text
As the base62 has lot more characters, we can easily create a small version of a given number.

### Let's do the Math

Converting to another base has common steps. (base-10-to-other-bases)
• Divide the number by the base and get the remainder.
• Divide the quotient and get the remainder.
• Continue this process untill the quotient is zero.
• Order the remainders from last to first.
We can try this process for hexa-decimal. As hexa-decimal is 16 chars, we need a way to represent that value. For that 0123456789ABCDEF are used.

``````42
42 / 16 = remainder 10, quotient 2
2 / 16 = remainder 2, quotient 0
Since 10 is A in hexa representation
42 = 2A in hexa-decimal number system.```
```
This same logic is applied for Base62. We can use 0-9A-Za-z characters to encoe base62.
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

```130
130 / 62 = remainder 6, quotient 2
2/ 62 = remainder 2, quotient 0
130 = 26
```
```1000
1000/ 62 = remainder 8, quotient 16
16/ 62 = remainder 16, quotient 0
1000 = G8
```

Noted how the 4 characters has represented only with 2 characters.

### Let's code

As the code is faily simple, I just add it here.

Note that I have added base58 as well. That is because 0OIl characters are hard to read. As 0(zero), I(capital i), O(capital o) and l(lower case L) characters look the same depending on the font, I prefer to use base58.

``````package com.slmanju.baseconverter;

public class Base10Encoder implements BaseEncoder {

private final int base;
private final String characters;

public final static BaseEncoder BASE_2 = new Base10Encoder(2, "01");
public final static BaseEncoder BASE_16 = new Base10Encoder(16, "0123456789ABCDEF");
public final static BaseEncoder BASE_62 = new Base10Encoder(62, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
public final static BaseEncoder BASE_58 = new Base10Encoder(58, "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");

public Base10Encoder(int base, String characters) {
this.base = base;
this.characters = characters;
}

@Override
public String encode(long number) {
StringBuilder stringBuilder = new StringBuilder(1);
do {
stringBuilder.insert(0, characters.charAt((int) (number % base)));
number /= base;
} while (number > 0);
return stringBuilder.toString();
}

@Override
public long decode(String number) {
long result = 0L;
int length = number.length();
for (int i = 0; i < length; i++) {
result += (long) Math.pow(base, i) * characters.indexOf(number.charAt(length - i - 1));
}
return result;
}

}
```
```
``````package com.slmanju.baseconverter;

public interface BaseEncoder {

String encode(long number);

long decode(String number);

}
```
```

Happy coding :)