Skip to content

Instantly share code, notes, and snippets.

@GregTonoski
Created May 25, 2023 07:57
Show Gist options
  • Save GregTonoski/e9ccd4c8f0ed092f0ac7679b17c4ebaa to your computer and use it in GitHub Desktop.
Save GregTonoski/e9ccd4c8f0ed092f0ac7679b17c4ebaa to your computer and use it in GitHub Desktop.
Convert a number from base36 to base16 (hexadecimal) numeral.
#!/bin/bash
# base36_to_hex.bash: convert a number from base36 to base16 (hexadecimal) numeral.
# Examples:
# $ bash base36_to_hex.bash ZYXWVTSRQPONMLKJIHGFEDCBA9876543210
declare STRING_BASE36_INPUT="$1"
declare -i -r FROM_BASE=36
declare -i -r DIVISOR=16
declare dividend=${STRING_BASE36_INPUT}
declare base16_digits=""
declare string_of_4digits_numbers=""
declare -i remainder=0
declare quotient=""
declare -i subdividend=0
declare quotient_digit=""
for (( i=0; i<${#STRING_BASE36_INPUT}; i++)); do
printf -v string_of_4digits_numbers "%s%04d" "${string_of_4digits_numbers}" $(( 36#${STRING_BASE36_INPUT:i:1} ))
done
declare dividend=${string_of_4digits_numbers}
while (( ${#dividend} >= ${#DIVISOR} )); do
for (( position=0; position<${#dividend}; position+=4 )); do
subdividend=$(( ${remainder} * ${FROM_BASE} + 10#${dividend:${position}:4} ))
if [ "${quotient:0:4}" = "0000" ]; then
printf -v quotient "%04d" $(( 10#${subdividend}/${DIVISOR} ))
else
printf -v quotient_digit "%04d" $(( 10#${subdividend}/${DIVISOR} ))
printf -v quotient "%s%s" "${quotient}" "${quotient_digit}"
fi
remainder=$(( 10#${subdividend}%${DIVISOR} ))
done
printf -v base16_digits "%01X%s" "${remainder}" "${base16_digits}"
if [ "${quotient}" = "0000" ]; then
break
fi
dividend=${quotient}
quotient=""
remainder=0
done
for (( position=${#base16_digits}; position < $(( 256/8*2 )); position+=1 )); do
base16_digits="0${base16_digits}"
done
printf "%s\n" "${base16_digits}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment