printing bit representation of numbers in python

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

    0 讨论(0)
  • 2020-12-13 06:22

    Slightly off-topic, but might be helpful. For better user-friendly printing I would use custom print function, define representation characters and group spacing for better readability. Here is an example function, it takes a list/array and the group width:

    def bprint(A, grp):
        for x in A:
            brp = "{:08b}".format(x)
            L=[]
            for i,b in enumerate(brp):
                if b=="1":
                    L.append("k")
                else: 
                    L.append("-")
                if (i+1)%grp ==0 :
                    L.append(" ")
    
            print "".join(L) 
    
    #run
    A = [0,1,2,127,128,255]
    bprint (A,4)
    

    Output:

    ---- ----
    ---- ---k
    ---- --k-
    -kkk kkkk
    k--- ----
    kkkk kkkk
    
    0 讨论(0)
  • 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}"
    
    0 讨论(0)
  • 2020-12-13 06:29

    This kind of thing?

    >>> ord('a')
    97
    >>> hex(ord('a'))
    '0x61'
    >>> bin(ord('a'))
    '0b1100001'
    
    0 讨论(0)
  • 2020-12-13 06:35

    The bin function

    0 讨论(0)
提交回复
热议问题