×
Create a new article
Write your page title here:
We currently have 3,189 articles on s23. Type your article name above or create one of the articles listed here!



    s23
    3,189Articles
    Revision as of 21:32, 12 November 2006 by imported>mutante

    <highlightSyntax>

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

    read -p "Give me a hex number " hex 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`
    echo "[$pos]: $digit = $ddigit * (16^$pos) = $ddigit * $factor = $subresult"
    let result=$result+$subresult
    let pos++
    let length--
    

    done

    echo "Result: $hex (hex) is $result (dec)" | boxes exit 0 </highlightSyntax>

     ./hex2dec.sh
    
    Give me a hex number 523F
    [0]: F = 15 * (16^0) = 15 * 1 = 15
    [1]: 3 = 3 * (16^1) = 3 * 16 = 48
    [2]: 2 = 2 * (16^2) = 2 * 256 = 512
    [3]: 5 = 5 * (16^3) = 5 * 4096 = 20480
    /*************************************/
    /* Result: 523F (hex) is 21055 (dec) */
    /*************************************/
    
    Cookies help us deliver our services. By using our services, you agree to our use of cookies.
    Cookies help us deliver our services. By using our services, you agree to our use of cookies.