Aashish sharma Sharma - 4 months ago 33

Python Question

I want to manipulate the binary number directly in python. For example I have decimal number 18. I was able to convert number into binary using

`seed =bin(18)`

but problem is I want to xor few of its bits.If I access this seed using array indexing I cant xor them as it is of type 'str'. How can simply take decimal number convert into binary and play with its bits?

Thanks in advance

Answer

You can use bitwise operations directly on integers. You can convert between binary strings and integers for printing/debugging by using `bin`

as you already know, and converting a string to binary using `int(binary_string, 2)`

.

```
seed = bin(18) # 0b10010
bitmask = '01101'
xor_result = 18 ^ int(bitmask, 2)
print(bin(xor_result)) # 0b11111
```