SCR/SCR1.2/TP06/any2dec_inv.sh

32 lines
654 B
Bash
Raw Normal View History

2022-11-29 15:40:14 +01:00
#!/bin/bash
#
# any2dec.sh <radix> <string_representation_in_that_radix>
#
if [[ $# -lt 2 ]]
then
echo "Usage: $0 <radix> <string_representation_in_that_radix>"
exit
fi
if [[ $1 -lt 2 || $1 -gt 36 ]]
then
echo "The radix is a decimal between 2 and 36"
exit
fi
DIGITS=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
LEGAL_DIGITS=$(expr substr $DIGITS 1 $1)
decimal=0
l=$(expr length $2)
for ((i=0;i<l;i++))
do
digit=$(expr substr $2 $((i+1)) 1)
pos=$(expr index $LEGAL_DIGITS $digit)
if [[ pos -eq 0 ]]
then
echo "Authorized digits are : $LEGAL_DIGITS"; exit
fi
digit_val=$((pos-1))
decimal=$((decimal*$1+digit_val))
done
echo "decimal : $decimal"
exit