Bitwise Operation on Float Tensor

Hello I’d like to ask how could I do bitwise operations on float tensors? Currently I have to use struct to convert them and then do the operation on CPU and move back, which is very inefficient… Do we have pytorch solutions for that?

Found previous questions like 6 years ago but no solutions there: Bitwise Operations on Cuda Float Tensor

On the other hand, is it possible to interpret a tensor as another type (not type cast)? For example, interpret a DoubleTensor as a LongTensor? If I can do this, I can then use bitwise operations just like those for integer types…

view should work as seen here:

a = torch.tensor(1., device="cuda")
b = a.view(torch.int)
print(b)
# tensor(1065353216, device='cuda:0', dtype=torch.int32)

# both represent this bit pattern
# 00111111 10000000 00000000 00000000 

and allows you to interpret the data in another format.

1 Like

Why doesn’t this work with doubles? When I try torch.float64, I don’t get matching bit patterns.

Could you post an example showing the issue in the same way I’ve shown it works?

Never mind, I think I resolved the issue. I was manually comparing with the results from these two IEEE754 converters from double to binary, but there are slight differences (e.g. the closest float to 3.1415):

The former seems to match what .view(torch.long) gives.