Skip to content

Instantly share code, notes, and snippets.

@GregTonoski
Created May 25, 2023 07:59
Show Gist options
  • Save GregTonoski/84f69973785dd4fb4369c993a62a90c7 to your computer and use it in GitHub Desktop.
Save GregTonoski/84f69973785dd4fb4369c993a62a90c7 to your computer and use it in GitHub Desktop.
Convert a number from base16 (hex) to base36 numeral.
#!/bin/bash
# hex_to_base36.bash: convert a number from base16 (hex) to base36 numeral.
# Examples:
# $ bash hex_to_base36.bash FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140
declare STRING_HEX_INPUT="$1"
declare -i -r DIVISOR=36
declare -i -r FROM_BASE=256
declare dividend=${STRING_HEX_INPUT}
declare string_of_base36_digits_in_hex=""
declare -i remainder=0
declare quotient=""
declare -i subdividend=0
declare quotient_digit=""
declare -r BASE36_CHARSET="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
declare -i base36_char_index=0
while (( ${#dividend} >= ${#DIVISOR} )); do
for (( position=0; position<${#dividend}; position+=2 )); do
subdividend=$(( ${remainder} * ${FROM_BASE} + 16#${dividend:${position}:2} ))
if [ "${quotient:0:2}" = "00" ]; then
printf -v quotient "%02X" $(( ${subdividend}/${DIVISOR} ))
else
printf -v quotient_digit "%02X" $(( ${subdividend}/${DIVISOR} ))
printf -v quotient "%s%s" "${quotient}" "${quotient_digit}"
fi
remainder=$(( ${subdividend}%${DIVISOR} ))
done
printf -v string_of_base36_digits_in_hex "%s%02X" "${string_of_base36_digits_in_hex}" "${remainder}"
if [ "${quotient}" = "00" ]; then
break
fi
dividend=${quotient}
quotient=""
remainder=0
done
for (( i=0; i < ${#string_of_base36_digits_in_hex} ; i+=2 )); do
base36_char_index=$(( 16#${string_of_base36_digits_in_hex:${i}:2} ))
printf -v result "%c%s" "${BASE36_CHARSET:${base36_char_index}:1}" "${result}"
done
printf "%s\n" "${result}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment