bash 将二进制转换为十进制_bash shell实现二进制与十进制数的互转

二进制转十进制#!/bin/bash

#b2d.sh: convert binary number to decimal number

#Usage: ./b2d.sh number

BAD_ARGS=65

WRONG_ARGS=66

ARGS=1 #参数数目

if [ $# -ne $ARGS ]

then

echo "Usage: `basename $0` binary_number"

exit $BAD_ARGS

fi

case $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_number

BAD_ARGS=65

WRONG_ARGS=66

ARGS=1 #参数数目

if [ $# -ne $ARGS ]

then

echo "Usage: `basename $0` decimal_number"

exit $BAD_ARGS

fi

function 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_ARGS

else

#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 0

fi

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值