Python int to binary string?

后端 未结 30 1610
执念已碎
执念已碎 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:40

    If you're looking for bin() as an equivalent to hex(), it was added in python 2.6.

    Example:

    >>> bin(10)
    '0b1010'
    
    0 讨论(0)
  • 2020-11-22 05:41

    This is for python 3 and it keeps the leading zeros !

    print(format(0, '08b'))
    

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

    Here is the code I've just implemented. This is not a method but you can use it as a ready-to-use function!

    def inttobinary(number):
      if number == 0:
        return str(0)
      result =""
      while (number != 0):
          remainder = number%2
          number = number/2
          result += str(remainder)
      return result[::-1] # to invert the string
    
    0 讨论(0)
  • 2020-11-22 05:42

    As the preceding answers mostly used format(), here is an f-string implementation.

    integer = 7
    bit_count = 5
    print(f'{integer:0{bit_count}b}')
    

    Output:

    00111

    For convenience here is the python docs link for formatted string literals: https://docs.python.org/3/reference/lexical_analysis.html#f-strings.

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

    Here's yet another way using regular math, no loops, only recursion. (Trivial case 0 returns nothing).

    def toBin(num):
      if num == 0:
        return ""
      return toBin(num//2) + str(num%2)
    
    print ([(toBin(i)) for i in range(10)])
    
    ['', '1', '10', '11', '100', '101', '110', '111', '1000', '1001']
    
    0 讨论(0)
  • 2020-11-22 05:43

    Yet another solution with another algorithm, by using bitwise operators.

    def int2bin(val):
        res=''
        while val>0:
            res += str(val&1)
            val=val>>1     # val=val/2 
        return res[::-1]   # reverse the string
    

    A faster version without reversing the string.

    def int2bin(val):
       res=''
       while val>0:
           res = chr((val&1) + 0x30) + res
           val=val>>1    
       return res 
    
    0 讨论(0)
提交回复
热议问题