printing bit representation of numbers in python

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

提交回复
热议问题