Given an number and an encoding length, how can I convert the number to its binary representation as a tensor?
Eg, given the number 6 and width 8, how can I obtain the tensor:
(0, 0, 0, 0, 0, 1, 1, 0)
def binary(x, bits):
mask = 2**torch.arange(bits).to(x.device, x.dtype)
return x.unsqueeze(-1).bitwise_and(mask).ne(0).byte()
If you wanna reverse the order of bits, use it with torch.arange(bits-1,-1,-1) instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With