echo $((2#$1)) 到底是做什麼的?

echo $((2#$1)) 到底是做什麼的?

以下 bash 腳本在給定二進制數時顯示十進制數。

echo $((2#$1))

究竟為什麼?

我理解這$1就是輸入。也許2是基數(二進制)。但我無法理解所使用的語法。

答案1

男人狂歡

   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.

[...]

   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))

[...]

   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.

答案2

來自文件: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))輸出255echo $((2#0110))輸出6

答案3

伊波爾的回答非常好,但有點不完整。 bash 手冊頁的引用部分指出該語法僅適用於常數,而非常數。你應該問這是怎麼回事[base#]n2#$1真的作品!

擴張

    擴展是在命令列上被分割成單字後執行的。執行的擴展有七種:大括號擴展、波形符擴展、參數和變數擴展、命令替換、算術擴展、分詞和路徑名擴展。

    展開的順序是:大括號展開;波形符擴展、參數和變數擴展、算術擴展和命令替換(以從左到右的方式完成);分詞;和路徑名擴展。

基本上 Bash 首先進行變數替換,因此$1首先用它的值替換。只有這樣它才會進行算術擴展,這只會看到一個適當的常數。

相關內容