Converting an integer to binary with a variable number of bits

I want to select a number from this list listand extract places from them from the nbits view .

I know that if I want 8 bits, I need to write

r = random.choice(list)
bin = "{0:08b}".format(r)

but i want to do something like

bin = "{0:0(self.n)b}".format(r)

where nis a member of the class.

How to do it?

+4
source share
2 answers

You can use nested a {…}to determine the size:

bin = "{0:0{1}b}".format(r, self.n)

And with Py2.7 + you can omit the numbers if you find it cleaner:

bin = "{:0{}b}".format(r, self.n)

For example:

>>> "{:0{}b}".format(9, 8)
'00001001'
+3
source

From python3.6, you can use Literal String Interpolation by adding variable names to your string.

In [81]: pad,num = 8,9

In [82]: f"{num:0{pad}b}"
Out[82]: '00001001'

Using str.format, you can also use names:

In [92]: pad,num = 8,9

In [93]: "{n:0{p}b}".format(n=num, p=pad)
Out[93]: '00001001'
+1
source

Source: https://habr.com/ru/post/1623350/


All Articles