【发布时间】:2013-07-04 10:56:29
【问题描述】:
我正在尝试制作一个将二进制数计算为十进制的小脚本。它的工作原理是这样的:
-获取“1”或“0”位作为单独的参数。例如“./bin2dec 1 0 0 0 1 1 1”。
-对于每个参数位:如果是'1',则乘以对应的2的幂(在上述情况下,最左边的'1'将是64),然后将其添加到'sum'变量中.
这是代码(在指出的地方是错误的):
#!/bin/bash
p=$((2**($#-1))) #Finds the power of two for the first parameter.
sum=0 #The sum variable, to be used for adding the powers of two in it.
for (( i=1; i<=$#; i++ )) #Counts all the way from 1, to the total number of parameters.
do
if [ $i -eq 1 ] # *THIS IS THE WRONG POINT* If parameter content equals '1'...
then
sum=$(($sum+$p)) #...add the current power of two in 'sum'.
fi
p=$(($p/2)) #Divides the power with 2, so to be used on the next parameter.
done
echo $sum #When finished show the 'sum' content, which is supposed to be the decimal equivalent.
我的问题在注意点(第 10 行,包括空白行)。在那里,我试图检查每个参数的内容是否等于 1。我怎样才能使用变量来做到这一点?
例如,$1 是第一个参数,$2 是第二个参数,以此类推。我希望它像 $i 一样,其中 'i' 是每次增加一的变量,以便与下一个参数匹配。
除其他外,我试过这个:'$(echo "$"$i)' 但没有用。
我知道我的问题很复杂,我努力尽可能地把它说清楚。 有什么帮助吗?
【问题讨论】:
-
附带说明:bash 可以像这样进行转换 -->
$ printf '%d\n' "$((2#1000111))"返回 71。 -
@fedorqui 或只是
echo $((2#1000111)) -
Ikr,我只是想要一个使用我上面那样的脚本。并找出我们是否以及如何使用变量来引用参数。
标签: bash variables loops for-loop parameters