Quantcast
Viewing all articles
Browse latest Browse all 74

Answer by Xiang for Python int to binary string?

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.


Viewing all articles
Browse latest Browse all 74

Trending Articles