Reputation: 483
I have an integer, and would like to cast it as a tuple of boolean-likes— {0, 1}
specifically. The way which comes to mind is tuple(int(b) for b in bin(my_int)[2:])
, but feels off. What is the idiomatic/canonical way perform this?
Edit: for clarity, if the integer is 3
, the tuple would be (0, 0, 0, 0, 0, 0, 1, 1)
. To further clarify, assume the integer is in {0, 1, …, 255}
and the tuple’s length should be eight. So what I have at this point (but aim to improve) is tuple(int(b) for b in bin(my_int)[2:].zfill(8))
Upvotes: 2
Views: 179
Reputation: 381
I don't think your way is bad, but I found another one:
def to_binary(num):
result = []
while num >= 1:
result.insert(0, num%2)
num//=2
return result
print(to_binary(5))
>>> [1, 0, 1]
Or you can add via append and at the end reverse via [::-1]
. To be honest, I don't remember which is faster.
UPD [07.07.2022]
As I understand it, you need a tuple, and if its length is less than eight characters, you need to complement it with 0 on the left.
In this case, the code will change a little:
def to_binary(num):
result = []
while num >= 1:
result.insert(0, num%2)
num//=2
result = tuple([0] * (max(8-len(result), 0)) + result)
return result
Or you can also update your code by adding zfill
method:
your_tuple = tuple(int(b) for b in bin(3)[2:].zfill(8))
Upvotes: 3