Skip to content

Latest commit

 

History

History
113 lines (79 loc) · 3.47 KB

ch8-2.md

File metadata and controls

113 lines (79 loc) · 3.47 KB

8.2. Numerical Constants

第八章第二節:數字常數

A shell script interprets a number as decimal (base 10), unless that number has a special prefix or notation.

一個 shell 腳本會以十進制 (基數為 10) 解讀一個數字,除非該數字有特殊的前綴或表示式。

A number preceded by a 0 is octal (base 8).

以 0 開頭的數字為八進制 (基數為 8)。

A number preceded by 0x is hexadecimal (base 16).

以 0x 開頭的數字為十六進制 (基數為 16)。

A number with an embedded # evaluates as BASE#NUMBER (with range and notational restrictions).

有嵌入 # 井號的數字將解讀為 BASE#NUMBER 表示式 (含範圍跟表示式限制)。

Example 8-4. Representation of numerical constants

範例 8-4. 數字常數的表示式

#!/bin/bash
# numbers.sh: Representation of numbers in different bases.
#             不同基數的數字表示式

# Decimal: the default
# 十進制: 為預設值
let "dec = 32"
echo "decimal number = $dec"             # 32
# Nothing out of the ordinary here.
# 這裡沒什麼特別的。


# Octal: numbers preceded by '0' (zero)
# 八進制: 以 '0' (零) 開頭的數字
let "oct = 032"
echo "octal number = $oct"               # 26
# Expresses result in decimal.
# --------- ------ -- -------
# 結果會以十進制表示。


# Hexadecimal: numbers preceded by '0x' or '0X'
# 十六進制: 以 '0x' 或 '0X' 開頭的數字
let "hex = 0x32"
echo "hexadecimal number = $hex"         # 50

echo $((0x9abc))                         # 39612
#     ^^      ^^   double-parentheses arithmetic expansion/evaluation
#                  雙層小括號會執行算術展開/運算
# Expresses result in decimal.
# 結果亦以十進制表示。



# Other bases: BASE#NUMBER
# 其他種基數表示式: BASE#NUMBER
# BASE between 2 and 64.
# 基數 BASE 必須介於 2 至 64 之間。
# NUMBER must use symbols within the BASE range, see below.
# 數字 NUMBER 使用的符號字元必須在基數 BASE 的範圍內, 詳情如下。


let "bin = 2#111100111001101"
echo "binary number = $bin"              # 31181

let "b32 = 32#77"
echo "base-32 number = $b32"             # 231

let "b64 = 64#@_"
echo "base-64 number = $b64"             # 4031
# This notation only works for a limited range (2 - 64) of ASCII characters.
# 此種表示式只能在一個有限範圍內 (2 - 64) 的 ASCII 字元下動作。
# 10 digits + 26 lowercase characters + 26 uppercase characters + @ + _
# 10 個數字 + 26 個小寫英文字母 + 26 個大寫英文字母 + @ + _


echo

echo $((36#zz)) $((2#10101010)) $((16#AF16)) $((53#1aA))
                                         # 1295 170 44822 3375


# Important note:
# 重要注意事項:
# --------------
# Using a digit out of range of the specified base notation
# 若表示式使用超出所指定基數範圍的數字
#+gives an error message.
#+則會出現錯誤訊息。

let "bad_oct = 081"
# (Partial) error message output:
# (部份) 輸出錯誤訊息:
#  bad_oct = 081: value too great for base (error token is "081")
#                 此數值對基數來說太大了 (錯誤 token 為 "081")
#              Octal numbers use only digits in the range 0 - 7.
#              八進制數值只能使用 0 - 7 範圍內的數字。

exit $?   # Exit value = 1 (error)
          # 退出值 = 1 (出錯)

# Thanks, Rich Bartell and Stephane Chazelas, for clarification.
# 感謝 Rich Bartell 與 Stephane Chazelas 釐清上述範例。