printing bit representation of numbers in python

后端 未结 5 835
终归单人心
终归单人心 2020-12-13 06:05

I want to print the bit representation of numbers onto console, so that I can see all operations that are being done on bits itself.

How can I possibly do it in pyth

5条回答
  •  长情又很酷
    2020-12-13 06:27

    From Python 2.6 - with the string.format method:

    "{0:b}".format(0x1234)
    

    in particular, you might like to use padding, so that multiple prints of different numbers still line up:

    "{0:16b}".format(0x1234)
    

    and to have left padding with leading 0s rather than spaces:

    "{0:016b}".format(0x1234)
    

    From Python 3.6 - with f-strings:

    The same three examples, with f-strings, would be:

    f"{0x1234:b}"
    f"{0x1234:16b}"
    f"{0x1234:016b}"
    

提交回复
热议问题