Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert integer to pytorch tensor of binary bits

Tags:

pytorch

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)
like image 309
Tom Hale Avatar asked Mar 05 '26 17:03

Tom Hale


1 Answers


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.

like image 101
Tiana Avatar answered Mar 08 '26 17:03

Tiana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!