bash shell实现二进制与十进制数的互转
#!/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 =~ ^*$ ]]
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
页:
[1]