# Convert integer to pytorch tensor of binary bits

Asked by At

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)
``````

## 2 Answers On
``````def decimal_to_binary_tensor(value, width=0):
string = format(value, '0{}b'.format(width))
binary = [0 if c == '0' else 1 for c in string]
return torch.tensor(binary, dtype=torch.uint8)
``````

Examples:

``````>>> print(decimal_to_binary_tensor(6, width=8))
tensor([0, 0, 0, 0, 0, 1, 1, 0], dtype=torch.uint8)

>>> print(decimal_to_binary_tensor(6))
tensor([1, 1, 0], dtype=torch.uint8)
`````` On

If the input is unsigned bytes and the output width is 8 bits:

``````>>> binary = np.unpackbits(np.array([0xaa, 0xf0], dtype=np.uint8))
>>> print(torch.tensor(binary))
tensor([1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0], dtype=torch.uint8)
``````

Note that `unpackbits()` only operates with `np.uint8`.