A note for yourself. If you feel like it, rewrite it properly.

Sometimes you want to convert a decimal number x to an n-digit binary number. (Mainly when searching all bits) You can use format at that time, but I couldn't remember how to write it, so Make a note of how to use it often.

Explanation of the code for when you forget.
The binary number of x with `bin (x >> i)`

is shifted by one digit.
I want only the last digit of the shifted number, so I calculate the remainder after dividing by 2.
Since it is necessary to return the bit-shifted one to int in order to calculate the remainder divided by 2.
As ʻint (bin, 2) `, the binary number is converted back to the decimal number. If you change the order of assigning to `

x_array_bin`, you can make it properly`

[0,0,0,1,1] `,
Since it is not so relevant in the bit full search, it is left as it is.

```
x = 3
n = 5
x_array_bin = [0 for _ in range(n)]
for i in range(n):
x_array_bin[i] = int(bin(x >> i),2)%2
print(x_array_bin)
#[1, 1, 0, 0, 0]
```

Recommended Posts