Convert hex to decimal

This is quite interesting, thought that I would post it. I wanted to convert a hexadecimal number to decimal in a shell script. I vaguely recall doing it once before, might have used the Busybox 'printf' applet -- but can't recall how I did that.

So, I did it using 'bc', the commandline math processor:

VARHEX='12'

VARDEC="`echo "ibase=16; ${VARHEX}; obase=10" | bc`"
echo "$VARDEC"


Note, 'bc' is not a Busybox applet. Busybox has another simpler maths applet called 'dc'. Most puppies should have 'bc'.


Posted on 8 Oct 2011, 18:09


Comments:

Posted on 8 Oct 2011, 22:11 by technosaurus
dec2basN
don't you just _love_ recursion.

#!/bin/ash

#note that base64 is traditionally A...Za...z0...9+/ (yeah wtf)
dec2baseN(){
A=$(($1/$2))
STRING=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/
[ $A -ge $2 ] && dec2baseN ${A} $2 || printf ${STRING:$A:1}
printf ${STRING:$(($1%$2)):1}
}

dec2baseN $1 $2



Posted on 8 Oct 2011, 23:12 by technosaurus
baseN2dec
and here is the baseN2dec in shell only


#!/bin/ash
#note that base64 is traditionally A...Za...z0...9+/
#base32 is different too
STRING=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/
i=$((${#1}-1));DEC=0;POS=1;BASE=${2:-16}
while ([ $i -ge 0 ]) do
VAL=${1:$i:1}
VAL=${STRING%${VAL}*}
VAL=${#VAL}
DEC=$(($VAL*$POS+$DEC))
POS=$(($BASE*$POS))
i=$(($i-1))
done
echo $DEC



Posted on 9 Oct 2011, 2:29 by 8-bit
re. Convert hex to decimal
Although technosaurus has shown a script that does the job, I can see that Barry's method uses less code and that is good in the interest of "keeping Puppy small".

Removal of few lines of unneeded code in every script made for Puppy would cut down on Puppy's size.
I have wondered if ALL comment lines were removed from all the Puppy scripts how much it would cut down the size of Puppy.

Of course, this would not give credit in the script to the creator of it so that is probably a no-no.



Posted on 15 Oct 2011, 3:28 by ak
ash
ash can do that ;)

echo $((0x60))