### vim:ft=zsh:foldmethod=marker
###
### convert numbers between different bases
###
### Frank Terbeck <ft@bewatermyfriend.org>
### Last-Modified: Wed Feb 4 12:26:23 2009
###
### URI: <http://ft.bewatermyfriend.org/comp/zsh.html>
###
setopt localoptions noksharrays
local from=${1[1]} to=${1[2]} num=$2
local -i from_c to_c
function Nconvert_getcode() {
local code=$1
case ${code} in
(h) (( code = 16 )) ;;
(d) (( code = 10 )) ;;
(o) (( code = 8 )) ;;
(b) (( code = 2 )) ;;
(*)
return 1
;;
esac
printf '%s' ${code}
return 0
}
if (( ${#@} < 2 )) ; then
printf 'usage: nconvert CONVERSION_CODE NUMBER\n'
printf ' eg.: nconvert dh 42\n'
printf ' returns '\''0x2A'\'' - decimal 42 converted to hex.\n'
printf ' available conversion chars: d, h, o and b\n'
return 2
fi
from_c=$(Nconvert_getcode ${from})
if [[ $? -ne 0 ]] ; then
printf 'Unknown from code: (%s)\n' ${from}
return 1
fi
to_c=$(Nconvert_getcode ${to})
if [[ $? -ne 0 ]] ; then
printf 'Unknown from code: (%s)\n' ${from}
return 1
fi
print -- $(( [#${to_c}] ${from_c}#${num} ))
return 0