Python int to binary string?

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

提交回复
热议问题