Python int to binary string?

后端 未结 30 1611
执念已碎
执念已碎 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 06:03

    As a reference:

    def toBinary(n):
        return ''.join(str(1 & int(n) >> i) for i in range(64)[::-1])
    

    This function can convert a positive integer as large as 18446744073709551615, represented as string '1111111111111111111111111111111111111111111111111111111111111111'.

    It can be modified to serve a much larger integer, though it may not be as handy as "{0:b}".format() or bin().

    0 讨论(0)
  • 2020-11-22 06:03

    Using numpy pack/unpackbits, they are your best friends.

    Examples
    --------
    >>> a = np.array([[2], [7], [23]], dtype=np.uint8)
    >>> a
    array([[ 2],
           [ 7],
           [23]], dtype=uint8)
    >>> b = np.unpackbits(a, axis=1)
    >>> b
    array([[0, 0, 0, 0, 0, 0, 1, 0],
           [0, 0, 0, 0, 0, 1, 1, 1],
           [0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8)
    
    0 讨论(0)
  • 2020-11-22 06:04

    Python's string format method can take a format spec.

    >>> "{0:b}".format(37)
    '100101'
    

    Format spec docs for Python 2

    Format spec docs for Python 3

    0 讨论(0)
  • 2020-11-22 06:04

    Somewhat similar solution

    def to_bin(dec):
        flag = True
        bin_str = ''
        while flag:
            remainder = dec % 2
            quotient = dec / 2
            if quotient == 0:
                flag = False
            bin_str += str(remainder)
            dec = quotient
        bin_str = bin_str[::-1] # reverse the string
        return bin_str 
    
    0 讨论(0)
  • 2020-11-22 06:05

    here is simple solution using the divmod() fucntion which returns the reminder and the result of a division without the fraction.

    def dectobin(number):
        bin = ''
        while (number >= 1):
            number, rem = divmod(number, 2)
            bin = bin + str(rem)
        return bin
    
    0 讨论(0)
  • 2020-11-22 06:06

    you can do like that :

    bin(10)[2:]
    

    or :

    f = str(bin(10))
    c = []
    c.append("".join(map(int, f[2:])))
    print c
    
    0 讨论(0)
提交回复
热议问题