Advanced Bash-Scripting Guide: A complete guide to shell scripting, using Bash | ||
---|---|---|
Prev | Chapter 8. Operations and Related Topics | Next |
A shell script interprets a number as decimal (base 10), unless that number has a special prefix or notation. A number preceded by a 0 is octal (base 8). A number preceded by 0x is hexadecimal (base 16). A number with an embedded # is evaluated as BASE#NUMBER (this option is of limited usefulness because of range restrictions).
Example 8-3. Representation of numerical constants:
1 #!/bin/bash 2 # numbers.sh: Representation of numbers. 3 4 # Decimal 5 let "d = 32" 6 echo "d = $d" 7 # Nothing out of the ordinary here. 8 9 10 # Octal: numbers preceded by '0' (zero) 11 let "o = 071" 12 echo "o = $o" 13 # Expresses result in decimal. 14 15 # Hexadecimal: numbers preceded by '0x' or '0X' 16 let "h = 0x7a" 17 echo "h = $h" 18 # Expresses result in decimal. 19 20 # Other bases: BASE#NUMBER 21 # BASE between 2 and 36. 22 let "b = 32#77" 23 echo "b = $b" 24 # 25 # This notation only works for a limited range (2 - 36) 26 # ... 10 digits + 26 alpha characters = 36. 27 let "c = 2#47" # Out of range error: 28 # numbers.sh: let: c = 2#47: value too great for base (error token is "2#47") 29 echo "c = $c" 30 31 echo 32 33 echo $((36#zz)) $((2#10101010)) $((16#AF16)) 34 35 exit 0 36 # Thanks, S.C., for clarification. |