Bash Base62 Sample Code

Find Bash script examples for encoding and decoding data with Base62 in your shell environment.


#!/bin/bash

CHARSET="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

encode() {
    local input="$1"
    local bytes
    bytes=$(echo -n "$input" | xxd -p -c 256)
    local result=""
    local value=0
    local bits=0

    for (( i=0; i<${#bytes}; i+=2 )); do
        local byte="0x${bytes:$i:2}"
        value=$(( (value << 8) | byte ))
        bits=$(( bits + 8 ))
        while (( bits >= 6 )); do
            result+="${CHARSET:$(( (value >> (bits - 6)) & 0x3F )):1}"
            bits=$(( bits - 6 ))
        done
    done

    if (( bits > 0 )); then
        result+="${CHARSET:$(( (value << (6 - bits)) & 0x3F )):1}"
    fi

    echo "$result"
}

decode() {
    local input="$1"
    local value=0
    local bits=0
    local result=""

    for (( i=0; i<${#input}; i++ )); do
        local char="${input:$i:1}"
        value=$(( (value << 6) | $(expr index "$CHARSET" "$char" - 1) ))
        bits=$(( bits + 6 ))
        if (( bits >= 8 )); then
            result+=$(printf "\\x%02x" $(( (value >> (bits - 8)) & 0xFF )))
            bits=$(( bits - 8 ))
        fi
    done

    echo -e "$result"
}

# Usage
input="回□〓≡╝╚╔╗"
encoded=$(encode "$input")
echo "Encoded: $encoded"

decoded=$(decode "$encoded")
echo "Decoded: $decoded"
Base62 Sample Code