二进制转十进制

#!/bin/bash#b2d.sh: convert binary number to decimal number#Usage: ./b2d.sh numberBAD_ARGS=65WRONG_ARGS=66ARGS=1                                          #参数数目if [ $# -ne $ARGS ]then    echo "Usage: `basename $0` binary_number"    exit $BAD_ARGSficase $1 in    [01]*)                                      #判断是否为二进制数        count=$(echo $1 | wc -c)        let "count--"                           #求出所输入的二进制数的位数                                i=0        n=$count        result=0        while [ $i -lt $count ]        do            c=$(echo $1 | cut -b$n)             #从最低位开始依次得到该位上的数,如1101,将依次得到1、0、1、1            let "result+=c*2**i"                #依次累加转换为十进制数            let "i++"            let "n--"        done        echo "The decimal number of $1 is $result."        exit 0        ;;    *)        echo "Please run this script with a binary number"        exit $WRONG_ARGS        ;;esac

十进制转二进制

#!/bin/bash#d2b.sh: convert a decimal number to a binary number#Usage: ./d2b.sh decimal_numberBAD_ARGS=65WRONG_ARGS=66ARGS=1                                          #参数数目if [ $# -ne $ARGS ]then    echo "Usage: `basename $0` decimal_number"    exit $BAD_ARGSfifunction is_positive_int()                      #用于判断输入是否为正整数,是返回1,否返回0{    if [ $# -lt 1 ]    then        return 0    fi    if [[ $1 =~ ^[1-9][0-9]*$ ]]    then        return 1    fi    if [[ $1 =~ ^0$ ]]    then        return 1    fi    return 0}is_positive_int $1                              #调用该函数进行判断if [ $? -ne 1 ]                                 #不为1,则不是十进制正整数,提示并退出                   then    echo "Please run this script with a decimal number."    exit $WRONG_ARGSelse    #echo "$1 is a decimal number."    num=$1    while [ $num -gt 0 ]                        #辗转相除法    do        let r=num%2        result=$r$result        let num=num/2    done    echo "The binary number of $1 is $result."    exit 0fi