printing bit representation of numbers in python

后端 未结 5 782
终归单人心
终归单人心 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:13

    In Python 2.6+:

    print bin(123)
    

    Results in:

    0b1111011
    

    In python 2.x

    >>> binary = lambda n: n>0 and [n&1]+binary(n>>1) or []
    >>> binary(123)
    [1, 1, 0, 1, 1, 1, 1]
    

    Note, example taken from: "Mark Dufour" at http://mail.python.org/pipermail/python-list/2003-December/240914.html

提交回复
热议问题