Hexadecimal To Decimal in Shell Script

前端 未结 8 2272
北恋
北恋 2020-11-29 15:34

Can someone help me to convert a hexadecimal number to decimal number in a shell script?

E.g., I want to convert the hexadecimal number bfca3000 to deci

8条回答
  •  猫巷女王i
    2020-11-29 16:03

    The error as reported appears when the variables are null (or empty):

    $ unset var3 var4; var5=$(($var4-$var3))
    bash: -: syntax error: operand expected (error token is "-")
    

    That could happen because the value given to bc was incorrect. That might well be that bc needs UPPERcase values. It needs BFCA3000, not bfca3000. That is easily fixed in bash, just use the ^^ expansion:

    var3=bfca3000; var3=`echo "ibase=16; ${var1^^}" | bc`
    

    That will change the script to this:

    #!/bin/bash
    
    var1="bfca3000"
    var2="efca3250"
    
    var3="$(echo "ibase=16; ${var1^^}" | bc)"
    var4="$(echo "ibase=16; ${var2^^}" | bc)"
    
    var5="$(($var4-$var3))"
    
    echo "Diference $var5"
    

    But there is no need to use bc [1], as bash could perform the translation and substraction directly:

    #!/bin/bash
    
    var1="bfca3000"
    var2="efca3250"
    
    var5="$(( 16#$var2 - 16#$var1 ))"
    
    echo "Diference $var5"
    

    [1]Note: I am assuming the values could be represented in 64 bit math, as the difference was calculated in bash in your original script. Bash is limited to integers less than ((2**63)-1) if compiled in 64 bits. That will be the only difference with bc which does not have such limit.

提交回复
热议问题