Python int to binary string?

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

    A simple way to do that is to use string format, see this page.

    >> "{0:b}".format(10)
    '1010'
    

    And if you want to have a fixed length of the binary string, you can use this:

    >> "{0:{fill}8b}".format(10, fill='0')
    '00001010'
    

    If two's complement is required, then the following line can be used:

    '{0:{fill}{width}b}'.format((x + 2**n) % 2**n, fill='0', width=n)
    

    where n is the width of the binary string.

提交回复
热议问题