Convert hex to decimal
October 08, 2011 —
BarryK
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'.
Comments
dec2basNUsername: technosaurus
don't you just _love_ recursion. [code] #!/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 [/code]
baseN2dec
Username: technosaurus
"and here is the baseN2dec in shell only [code] #!/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[/code]
re. Convert hex to decimal
Username: 8-bit
"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.
ash
Username: ak
"ash can do that ;) echo $((0x60))
Tags: puppy