9
8

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.

[bash]プレフィックスが0の数字を含んだ計算ができない

Last updated at Posted at 2015-10-29

次のコードをzshで実行すると、

echo $(( 049*2 ))
98

と予想通りの結果になる。

一方、次のコードをbashで実行すると、

bash-4.1$ echo $(( 049*2 ))
bash: 049: ベースの値には大きすぎます (error token is "049")

と怒られる。これはbashでは0で始まる数字は8進数として解釈されるためだということがわかった。0xあるいは0Xで始まる場合は16進数として解釈されることは知っていたが、これは知らなかった...いい勉強になりました。ではどうすれば10進数として解釈させることができるかですが、次のように数字の前に10#と書けばOK。

bash-4.1$ echo $(( 10#049*2 ))
98

一般に、ある数字をn進数で解釈させたい場合はn#を数字の前に書けばOK。

参考サイト

9
8
0

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
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?