将整数转换为二进制位的pytorch张量 [英] Convert integer to pytorch tensor of binary bits
本文介绍了将整数转换为二进制位的pytorch张量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个数字和一个编码长度,我如何将数字转换为张量的二进制表示?
Given an number and an encoding length, how can I convert the number to its binary representation as a tensor?
例如,给定数字6
和宽度8
,我如何获得张量:
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()
如果您想反转位的顺序,请将其与 torch.arange(bits-1,-1,-1)
一起使用.
If you wanna reverse the order of bits, use it with torch.arange(bits-1,-1,-1)
instead.
这篇关于将整数转换为二进制位的pytorch张量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文