I wanted to do this calculation a * 256 ** 3 + b * 256 ** 2 + c * 256 + d and assign output to variable and print dec.
我想做这个计算a * 256 ** 3 + b * 256 ** 2 + c * 256 + d并将输出分配给变量并打印dec。
dec ='a * 256 ** 3 + b * 256 ** 2 + c * 256 + d'
echo $dec
I am getting syntax error with the above lines.
我在上面的行中遇到语法错误。
2 个解决方案
#1
First of all, assignment is done this way
首先,分配是这样完成的
dec='a * 256 ** 3 + b * 256 ** 2 + c * 256 + d'
This is where your syntax error come from. Then you just have to evaluate your string with the operator $(( )) this way :
这是您的语法错误来自的地方。然后你只需用运算符$(())来评估你的字符串:
echo $((dec))
#2
For integer arithmetic, you can use the shell:
对于整数运算,您可以使用shell:
dec=$(( a * 256 ** 3 + b * 256 ** 2 + c * 256 + d ))
echo "$dec"
This uses an arithmetic context (( ... ))
to calculate the value.
这使用算术上下文((...))来计算值。
Note that there is no space in an assignment, this is important!
请注意,作业中没有空格,这很重要!
The shell does not support floating point arithmetic, but bc
or awk
do. For example, using awk (and assuming that you have shell variables $a
, $b
, $c
and $d
defined):
shell不支持浮点运算,但bc或awk支持。例如,使用awk(并假设您定义了shell变量$ a,$ b,$ c和$ d):
awk -v a="$a" -v b="$b" -v c="$c" -v d="$d" 'BEGIN{print a * 256 ** 3 + b * 256 ** 2 + c * 256 + d}'
or using bc:
或使用bc:
printf '%s * 256 ^ 3 + %s * 256 ^ 2 + %s * 256 + %s\n' "$a" "$b" "$c" "$d" | bc -l
Using the string format specifier %s
for each of the shell variables means that no precision is lost before passing the values to bc.
对每个shell变量使用字符串格式说明符%s意味着在将值传递给bc之前不会丢失任何精度。
#1
First of all, assignment is done this way
首先,分配是这样完成的
dec='a * 256 ** 3 + b * 256 ** 2 + c * 256 + d'
This is where your syntax error come from. Then you just have to evaluate your string with the operator $(( )) this way :
这是您的语法错误来自的地方。然后你只需用运算符$(())来评估你的字符串:
echo $((dec))
#2
For integer arithmetic, you can use the shell:
对于整数运算,您可以使用shell:
dec=$(( a * 256 ** 3 + b * 256 ** 2 + c * 256 + d ))
echo "$dec"
This uses an arithmetic context (( ... ))
to calculate the value.
这使用算术上下文((...))来计算值。
Note that there is no space in an assignment, this is important!
请注意,作业中没有空格,这很重要!
The shell does not support floating point arithmetic, but bc
or awk
do. For example, using awk (and assuming that you have shell variables $a
, $b
, $c
and $d
defined):
shell不支持浮点运算,但bc或awk支持。例如,使用awk(并假设您定义了shell变量$ a,$ b,$ c和$ d):
awk -v a="$a" -v b="$b" -v c="$c" -v d="$d" 'BEGIN{print a * 256 ** 3 + b * 256 ** 2 + c * 256 + d}'
or using bc:
或使用bc:
printf '%s * 256 ^ 3 + %s * 256 ^ 2 + %s * 256 + %s\n' "$a" "$b" "$c" "$d" | bc -l
Using the string format specifier %s
for each of the shell variables means that no precision is lost before passing the values to bc.
对每个shell变量使用字符串格式说明符%s意味着在将值传递给bc之前不会丢失任何精度。