Java convert String text to base36 and from base36 to hex

2.9k Views Asked by At

Is there any api in java to convert simple string to base36/base10 and from base36/base10 to hex representation.

example: input: '-22EEVX' encoding base36 output: f8 8d 33 23

2

There are 2 best solutions below

6
Krzysztof Krasoń On BEST ANSWER

Use Integer class and radix parameter of parseInt, and toHexString from the same class.

Integer.toHexString(Integer.parseInt("-22EEVX", 36));

For base10 it is even shorter (you omit radix parameter, it is assumed 10):

Integer.toHexString(Integer.parseInt("-22"));
0
Dilip Singh Kasana On

It may be useful to you If you want any string to encode and decode in base36.To use it in base 10 replace all 36 in below code to 10.

import java.math.BigInteger;

public class Base36 {

public static void main(String[] args) {
    String str = convertHexToBase36(toHex("8978675cyrhrtgdxfawW#$#$@$#"));
    System.out.println(str);
    String back = convertBase36ToHex(str);
    System.out.println(fromHex(back));

}

public static String fromHex(String hex) {
    StringBuilder output = new StringBuilder();
    for (int i = 0; i < hex.length(); i += 2) {
        String str = hex.substring(i, i + 2);
        output.append((char) Integer.parseInt(str, 16));
    }
    return output.toString();
}

public static String convertHexToBase36(String hex) {
    BigInteger big = new BigInteger(hex, 16);
    StringBuilder sb = new StringBuilder(big.toString(36));
    return sb.reverse().toString();
}

public static String convertBase36ToHex(String b36) {
    StringBuilder sb = new StringBuilder(b36);
    BigInteger base = new BigInteger(sb.reverse().toString(), 36);
    return base.toString(16);
}

public static String toHex(String arg) {
    return String.format("%040x", new BigInteger(1, arg.getBytes()));
}
}