imported>mutante mNo edit summary |
imported>mutante m (Category:Math) |
||
(7 intermediate revisions by the same user not shown) | |||
Line 1:
A [[bash]] script to convert hexadecimal to decimal numbers.
<highlightSyntax>
#!/bin/bash
Line 4 ⟶ 6:
# mutante (s23.org) 11/2006
if [ ! -n "$1" ]
read -p "Give me a hex number " hex▼
then
▲read -p "Give me a hex number: " hex
else
hex=$1
fi
length=${#hex}
i=0
Line 13 ⟶ 21:
do
digit=${hex:$length:1}
case "$digit" in
A | a) ddigit=10;;
Line 22 ⟶ 29:
F | f) ddigit=15;;
[0-9]) ddigit=$digit;;
*) echo "Bad input. Only 0-9 and
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++
Line 32 ⟶ 39:
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>
<pre>
./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) --
---------------------------------------
</pre>
* needs "[[bc]]" and "[[boxes]]"
[[Category:Linux]]
[[Category:Scripts]]
[[Category:Math]]
|
Latest revision as of 19:32, 16 November 2006
A bash script to convert hexadecimal to decimal numbers.
<highlightSyntax>
- !/bin/bash
- hex to decimal number converter
- 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) -- ---------------------------------------