shell------ conevrt binary to decimal

#!/bin/bash

help()
{
    cat<<HELP
    b2d-convert binary to decmial
    USEAGE:b2d [-h] binarynum
    OPTION:-h text help
    EXAMPLE:b2d 111010
    will return 58
HELP
    exit 0
}

error()
{
    echo "$1"
    exit 1
}
lastchar()
{
    if [ -z "$1" ];then
        reval=""
        return
    fi

    numofchar=$(echo -n "$1" | sed 's/ //g'| wc -c)

    reval=$(echo -n "$1" | cut -b "$numofchar")

}

chop()
{
    if [ -z "$1" ]; then
        rval=""
        return
    fi
    numofchar1=$(expr "$numofchar" - 1)
    

    
    reval=$(echo -n "$1" | cut -b 1-${numofchar1})
    
 
}

while [ -n  "$1" ];do
    case $1 in
        -h)help;shift1;;
        --)shift;break;;
        -*)error "error:no such option $1. -h for help";;
        *)break;;
    esac
done


sum=0
weight=1

[ -z "$1" ]&&help

binnum="$1"

while [ -n "$binnum" ];do
    lastchar "$binnum"
    if [ "$reval" = "1" ];then
    sum=$(expr "$sum" + "$weight")
    echo "sum is ${sum}"
    fi
    if [ "$binnum" = "0" ];then break; fi
    if [ "$binnum" = "1" ];then break; fi
    chop $binnum
    binnum=$reval
    echo "$binnum"
    weight=$(expr "$weight" "*" 2)
    echo "$weight"
done

echo -e "hello ,$USER.\n\n $1 binry to decmial $sum"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值