9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Zshでn進数を扱うには

Posted at

Bashでn進数を扱うにはを見て、zshでもやってみた。微妙に違うみたい。

# 2進数
echo $(( 2#101 ))         # 5
echo $(( 2#101 & 2#100 )) # 4 (=2#100)

# 8進数
# zshはデフォルトでは0から始まる数値を8進数とみなさない
echo $(( 0744 ))   # 744

# OCTAL_ZEROESをセットすると0から始まる数値を8進数として扱える
setopt OCTAL_ZEROES
echo $(( 0744 ))   # 484

# 8進数(続き)
echo $(( 8#744 ))  # 484
echo $(( 8#0744 )) # 484

# 16進数
echo $(( 0xff ))  # 255
echo $(( 16#ff )) # 255

# 36進数
echo $(( 36#10 )) # 36
echo $(( 36#zz )) # 1295

# zshの場合は大文字小文字区別なしで36進数までらしい
echo $(( 37#10 )) # invalid base (must be 2 to 36 inclusive): 37

#----------------------------
# zshは数値に基数を設定できる

# 16進数で表現
# 出力は上記のインプットとして使える形式になる
echo $(( [#16] 255 )) # 16#FF
# "##"にすると基数の情報なしになる
echo $(( [##16] 255 )) # FF

# 2進数から16進数へ
echo $(( [##16] 2#1011 )) # B

# 基数を設定した変数
typeset -i 16 x
x=255
echo $x # 16#FF

詳しくはman zshmiscARITHMETIC EVALUATIONを。

Arithmetic Evaluation
http://zsh.sourceforge.net/Doc/Release/Arithmetic-Evaluation.html

9
9
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?