Python int to binary string?

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

提交回复
热议问题