Python int to binary string?

后端 未结 30 1614
执念已碎
执念已碎 2020-11-22 05:34

Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?

There are a myriad of dec2bin() functions out on Google... But I

相关标签:
30条回答
  • 2020-11-22 05:53
    def binary(decimal) :
        otherBase = ""
        while decimal != 0 :
            otherBase  =  str(decimal % 2) + otherBase
            decimal    //=  2
        return otherBase
    
    print binary(10)
    

    output:

    1010

    0 讨论(0)
  • 2020-11-22 05:54

    Unless I'm misunderstanding what you mean by binary string I think the module you are looking for is struct

    0 讨论(0)
  • 2020-11-22 05:55

    For those of us who need to convert signed integers (range -2**(digits-1) to 2**(digits-1)-1) to 2's complement binary strings, this works:

    def int2bin(integer, digits):
        if integer >= 0:
            return bin(integer)[2:].zfill(digits)
        else:
            return bin(2**digits + integer)[2:]
    

    This produces:

    >>> int2bin(10, 8)
    '00001010'
    >>> int2bin(-10, 8)
    '11110110'
    >>> int2bin(-128, 8)
    '10000000'
    >>> int2bin(127, 8)
    '01111111'
    
    0 讨论(0)
  • 2020-11-22 05:57

    one-liner with lambda:

    >>> binary = lambda n: '' if n==0 else binary(n/2) + str(n%2)
    

    test:

    >>> binary(5)
    '101'
    



    EDIT:

    but then :(

    t1 = time()
    for i in range(1000000):
         binary(i)
    t2 = time()
    print(t2 - t1)
    # 6.57236599922
    

    in compare to

    t1 = time()
    for i in range(1000000):
        '{0:b}'.format(i)
    t2 = time()
    print(t2 - t1)
    # 0.68017411232
    
    0 讨论(0)
  • 2020-11-22 05:57

    If you are willing to give up "pure" Python but gain a lot of firepower, there is Sage - example here:

    sage: a = 15
    sage: a.binary()
    '1111'
    

    You'll note that it returns as a string, so to use it as a number you'd want to do something like

    sage: eval('0b'+b)
    15
    
    0 讨论(0)
  • 2020-11-22 05:59

    numpy.binary_repr(num, width=None)

    Examples from the documentation link above:

    >>> np.binary_repr(3)
    '11'
    >>> np.binary_repr(-3)
    '-11'
    >>> np.binary_repr(3, width=4)
    '0011'
    

    The two’s complement is returned when the input number is negative and width is specified:

    >>> np.binary_repr(-3, width=3)
    '101'
    >>> np.binary_repr(-3, width=5)
    '11101'
    
    0 讨论(0)
提交回复
热议问题