以下 bash 脚本在给定二进制数时显示十进制数。
echo $((2#$1))
Run Code Online (Sandbox Code Playgroud)
为什么?
我明白这$1是输入。也许2是基础(二进制)。但我无法理解使用的语法。
Ipo*_*cer 75
男人 bash
echo [-neE] [arg ...]
Output the args, separated by spaces, followed by a newline.
The return status is 0 unless a write error occurs. If -n is
specified, the trailing newline is suppressed. If the -e option
is given, interpretation of the following backslash-escaped
characters is enabled.
Run Code Online (Sandbox Code Playgroud)
[...]
Arithmetic Expansion
Arithmetic expansion allows the evaluation of an arithmetic expression
and the substitution of the result. The format for arithmetic expan?
sion is:
$((expression))
Run Code Online (Sandbox Code Playgroud)
[...]
Constants with a leading 0 are interpreted as octal numbers. A leading
0x or 0X denotes hexadecimal. Otherwise, numbers take the form
[base#]n, where the optional base is a decimal number between 2 and 64
representing the arithmetic base, and n is a number in that base. If
base# is omitted, then base 10 is used. When specifying n, the digits
greater than 9 are represented by the lowercase letters, the uppercase
letters, @, and _, in that order. If base is less than or equal to 36,
lowercase and uppercase letters may be used interchangeably to repre?
sent numbers between 10 and 35.
Run Code Online (Sandbox Code Playgroud)
小智 31
来自文档:https : //tiswww.case.edu/php/chet/bash/bashref.html#Shell-Arithmetic
带有前导 0 的常量被解释为八进制数。前导“0x”或“0X”表示十六进制。否则,数字采用 [base#]n 形式,其中可选基数是 2 到 64 之间的十进制数,表示算术基数,n 是该基数中的数字。如果省略 base#,则使用基数 10。指定 n 时,大于 9 的数字按小写字母、大写字母、“@”和“_”的顺序表示。如果基数小于或等于 36,小写和大写字母可以互换使用来表示 10 到 35 之间的数字。
所以echo $((16#FF))输出255和echo $((2#0110))输出6
小智 25
Ipor 的回答非常好,但有点不完整。bash 手册页的引用部分指出该语法仅适用于常量,而不是常量。你应该问这是如何真正起作用的![base#]n2#$1
扩张
拆分成单词后在命令行上进行扩展。执行的扩展有七种:大括号扩展、波浪号扩展、参数和变量扩展、命令替换、算术扩展、分词和路径名扩展。
展开的顺序是:大括号展开;波浪号扩展、参数和变量扩展、算术扩展和命令替换(以从左到右的方式完成);分词;和路径名扩展。
基本上 Bash 首先进行变量替换,因此$1首先用它的值替换。只有这样它才进行算术展开,它只看到一个适当的常数。
| 归档时间: |
|
| 查看次数: |
8379 次 |
| 最近记录: |