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

1 Answer

0 votes
/*
    Base-36 encoding/decoding in Rust using u128
    (limited to inputs that fit into 128 bits)
*/

const BASE36_DIGITS: &str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

fn encode_to_base36(text: &str) -> String {
    let bytes = text.as_bytes();

    // Convert bytes → u128 (base-256)
    let mut n: u128 = 0;
    for &b in bytes {
        n = n * 256 + b as u128;
    }

    // Convert u128 → Base-36
    if n == 0 {
        return "0".to_string();
    }

    let mut encoded = String::new();
    while n > 0 {
        let rem = (n % 36) as usize;
        encoded.push(BASE36_DIGITS.chars().nth(rem).unwrap());
        n /= 36;
    }

    encoded.chars().rev().collect()
}

fn decode_from_base36(encoded: &str) -> String {
    let encoded = encoded.to_uppercase();

    // Convert Base-36 → u128
    let mut n: u128 = 0;
    for c in encoded.chars() {
        let digit = BASE36_DIGITS.find(c).unwrap() as u128;
        n = n * 36 + digit;
    }

    // Convert u128 → bytes (base-256)
    if n == 0 {
        return String::new();
    }

    let mut bytes: Vec<u8> = Vec::new();
    while n > 0 {
        let rem = (n % 256) as u8;
        bytes.push(rem);
        n /= 256;
    }

    bytes.reverse();
    String::from_utf8(bytes).unwrap()
}

fn main() {
    let text = "Hello Universe!";
    let encoded = encode_to_base36(text);
    let decoded = decode_from_base36(&encoded);

    println!("Original: {}", text);
    println!("Base-36 encoded: {}", encoded);
    println!("Decoded: {}", decoded);
}


/*
run:

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

*/

 



answered 3 days ago by avibootz
...