Convert a hex string into base 36 encoded string and vice versa in Java

I am surfing around from quite some time for a proper solution for the above question.

I could not find the solution for the conversion/encoding in Java language.

I need to encode a hex string into base 36 formatted string.

For example, these are sample inputs and outputs.

ID and reversed B36 encoding

3028354D8202028000000000,CHL58FYDITHJ83VN0G1 3028354D8202028000000001,DHL58FYDITHJ83VN0G1 3028354D8202028000000002,EHL58FYDITHJ83VN0G1

Suggestions are highly appreciated.

Upvotes: 2

Views: 6491

Answers (2)

rossum
rossum

Reputation: 15685

Have you tried:

String convertHexToBase36(String hex) {
  BigInteger big = new BigInteger(hex, 16);
  return big.toString(36);
}

Upvotes: 9

Thanks @rossum for your help and patience.

I could now do a conversion from hex to base36 and vice-versa as per my requirements.

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);
}

I just did reverse B36 encoding. Loads of applause to @rossum for his patience and help.

Upvotes: 1

Related Questions