Quantcast
Viewing latest article 19
Browse Latest Browse All 74

Answer by Xiang for Convert int to binary string in Python

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 latest article 19
Browse Latest Browse All 74

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>