Java Base62 Sample Code
Learn how to implement Base62 encoding and decoding in Java with comprehensive code examples.
package tools;
import java.nio.charset.StandardCharsets;
import java.math.BigInteger;
import java.util.Arrays;
public class Base62 {
private static final String BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public static String encode(byte[] input) {
if (input.length == 0) {
return "";
}
BigInteger value = new BigInteger(1, input);
StringBuilder result = new StringBuilder();
while (value.compareTo(BigInteger.ZERO) > 0) {
BigInteger[] divmod = value.divideAndRemainder(BigInteger.valueOf(62));
result.append(BASE62.charAt(divmod[1].intValue()));
value = divmod[0];
}
for (byte b : input) {
if (b == 0) {
result.append(BASE62.charAt(0));
} else {
break;
}
}
return result.reverse().toString();
}
public static byte[] decode(String input) {
if (input.length() == 0) {
return new byte[0];
}
BigInteger value = BigInteger.ZERO;
for (char c : input.toCharArray()) {
value = value.multiply(BigInteger.valueOf(62)).add(BigInteger.valueOf(BASE62.indexOf(c)));
}
byte[] bytes = value.toByteArray();
if (bytes[0] == 0) {
bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
}
int leadingZeroes = 0;
for (char c : input.toCharArray()) {
if (c == BASE62.charAt(0)) {
leadingZeroes++;
} else {
break;
}
}
byte[] result = new byte[leadingZeroes + bytes.length];
System.arraycopy(bytes, 0, result, leadingZeroes, bytes.length);
return result;
}
public static void main(String[] args) {
// Encoding example
String input = "回□〓≡╝╚╔╗";
String encoded = Base62.encode(input.getBytes(StandardCharsets.UTF_8));
System.out.println("Encoded: " + encoded);
// Decoding example
String decoded = new String(Base62.decode(encoded), StandardCharsets.UTF_8);
System.out.println("Decoded: " + decoded);
}
}