Python int to binary string?

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

提交回复
热议问题