Hex2dec

From s23
Jump to navigation Jump to search

A bash script to convert hexadecimal to decimal numbers.

<highlightSyntax>

  1. !/bin/bash
  2. hex to decimal number converter
  3. mutante (s23.org) 11/2006

if [ ! -n "$1" ] then read -p "Give me a hex number: " hex else hex=$1 fi

length=${#hex} i=0 result=0 let length-- pos=0 while [ $length -ge 0 ]; do digit=${hex:$length:1} case "$digit" in A | a) ddigit=10;; B | b) ddigit=11;; C | c) ddigit=12;; D | d) ddigit=13;; E | e) ddigit=14;; F | f) ddigit=15;; [0-9]) ddigit=$digit;;

  • ) echo "Bad input. Only 0-9 and A-F are allowed."; exit 1;;

esac factor=`echo "(16^$pos)" | bc` subresult=`echo "$factor*$ddigit" | bc` if [ ! -n "$1" ]; then echo "[$pos]: $digit => $ddigit * (16^$pos) = $ddigit * $factor = $subresult +" | boxes -d ada-cmt; fi let result=$result+$subresult let pos++ let length-- done

if [ ! -n "$1" ]; then echo "Result: $hex (hex) is $result (dec)" | boxes -d ada-box; else echo "$hex (hex) = $result (dec)"; fi exit 0 </highlightSyntax>

 ./hex2dec.sh AFFE23
AFFE23 (hex) = 11533859 (dec)

 ./hex2dec.sh
Give me a hex number: F712
-- [0]: 2 => 2 * (16^0) = 2 * 1 = 2 +
-- [1]: 1 => 1 * (16^1) = 1 * 16 = 16 +
-- [2]: 7 => 7 * (16^2) = 7 * 256 = 1792 +
-- [3]: F => 15 * (16^3) = 15 * 4096 = 61440 +
---------------------------------------
-- Result: F712 (hex) is 63250 (dec) --
---------------------------------------