How to encode and decode any string into Base‑36 in Java

1 Answer

0 votes
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;

/**
    Base‑36 encoding/decoding in Java
    -------------------------------------------
    Base‑36 digits: 0–9, A–Z

    Encoding:
      - Convert string → bytes → BigInteger (base‑256)
      - Convert BigInteger → base‑36 using toString(36)

    Decoding:
      - Convert base‑36 → BigInteger
      - Convert BigInteger → bytes → original string

    Java's BigInteger already supports:
      - Arbitrary‑precision arithmetic
      - Base conversion via toString(radix)
      - Parsing via new BigInteger(String, radix)

    This makes the implementation clean and efficient.
*/

public class Base36Codec {

    // Encode any string into Base‑36
    public static String encodeToBase36(String input) {
        /**
            Convert string → bytes (UTF‑8)
            Then interpret bytes as a positive BigInteger.
        */
        byte[] bytes = input.getBytes(StandardCharsets.UTF_8);
        BigInteger big = new BigInteger(1, bytes); // 1 = positive number

        /**
            Convert BigInteger → Base‑36 string
            BigInteger.toString(36) uses digits 0‑9 + a‑z.
            We convert to uppercase to match your specification.
        */
        return big.toString(36).toUpperCase();
    }

    // Decode Base‑36 back into the original string
    public static String decodeFromBase36(String encoded) {
        /**
            Convert Base‑36 text → BigInteger
        */
        BigInteger big = new BigInteger(encoded, 36);

        /**
            Convert BigInteger → bytes → original UTF‑8 string
        */
        byte[] bytes = big.toByteArray();

        /**
            BigInteger.toByteArray() may include a leading zero byte
            if the number's highest bit is set.
            We remove it if present.
        */
        if (bytes.length > 1 && bytes[0] == 0) {
            byte[] trimmed = new byte[bytes.length - 1];
            System.arraycopy(bytes, 1, trimmed, 0, trimmed.length);
            bytes = trimmed;
        }

        return new String(bytes, StandardCharsets.UTF_8);
    }

    // Usage
    public static void main(String[] args) {
        String text = "Hello Universe!";
        String encoded = encodeToBase36(text);
        String decoded = decodeFromBase36(encoded);

        System.out.println("Original: " + text);
        System.out.println("Base-36 encoded: " + encoded);
        System.out.println("Decoded: " + decoded);
    }
}


/*
run:

Original: Hello Universe!
Base-36 encoded: LP4N024HJ1YVBVD84Y8TYQP
Decoded: Hello Universe!

*/

 



answered 3 days ago by avibootz
edited 3 days ago by avibootz
...