0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[PowerShell] 2進表記の罠

Posted at

問題

ご存じのとおり、PowerShell 7 では0bプレフィックスを使って2進数を記述できます。
先日、「予想外」の事象に遭遇したのでメモしておきます。

では、問題です。次の整数の値は?

PowerShell 7.5.1
0b1000000   # 7桁
0b10000000  # 8桁
0b100000000 # 9桁
こうなりました。

image.png

結論

表題に「罠」と書きましたが、私が勉強不足なだけで公式に記載されています。

  • バイナリ文字列が 8 ビットの倍数である場合、最上位ビットは符号ビットとして扱われます

ただし、「8 ビットの倍数」では不正確で、8・16・32・64 ビットの場合に最上位ビットが符号ビットになるようです。

16進にも気をつけましょう

  • 長さが 8 の倍数である 16 進文字列の最初の桁が 8 以上の場合、数字は負の数として扱われます

image.png

反省の弁

今後は型サフィックスを習慣化するようにします...

image.png

型アクセラレータを使って文字列を変換する場合も符号の有無を意識して...

image.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?