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?

More than 3 years have passed since last update.

Python3で2進数の出力を見やすくする

Last updated at Posted at 2021-06-01

データ収集系の設定をするときに、直接レジストリのどこか特定のbitを変更したくなったりする。16進数と2進数の変換は、Python3を使うのが楽なのでよく利用しているのだが、特に2進数で桁が多くなるとわかりにくくて困っていた。解決方法を見つけたのでメモ。

  • hex() 16進数で表示
  • int() 10進数で表示
  • bin() 2進数で表示
  • 0x 16進数表示
  • 0o 16進数表示
  • 0b 2進数表示

大抵の場合はこれで良いのだが、2進数はすぐに桁がすごいことになるので普通に表示するともうよくわからない。

>>> bin(0x5642)
'0b101011001000010'

なので、formatを使う。

>>> '{:#0_b}'.format(0x5642)
'0b101_0110_0100_0010'

#をつけると出力に0bとか0xのが付くので何進数で表示しているのかがわかる。
_をつけると4桁毎に_をつけてくれるので比較的何桁目なのかが分かり易い。2進数が入力の時は、_で区切るとわかりやすくなる。数字の中の_は無視してくれる。

>>> hex(0b011_1001010_10_11)
'0x1cab'

参考
https://note.nkmk.me/python-format-zero-hex/

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