The torch.bitwise_xor() method performs an element-wise XOR operation on two tensors. But what happened in the bitwise XOR operation? The bitwise XOR (exclusive OR) operation compares corresponding bits of two numbers, returning 1 if exactly one of the bits is 1, and 0 otherwise.
Bitwise XOR Truth Table
Input A | Input B | A | B (Output) |
0 (False) | 0 (False) | 0 (False) |
0 (False) | 1 (True) | 1 (True) |
1 (True) | 0 (False) | 1 (True) |
1 (True) | 1 (True) | 0 (False) |
Now, take a look at the figure below to see how this works in PyTorch.

From the above figure, you can see that we performed an XOR operation between integers 1 and 2, and the output is integer 3. How did we get that? We performed a bitwise XOR operation for each bit, and it returned a value based on the bitwise XOR truth table.
Syntax
torch.bitwise_xor(input, other, out=None)
Parameters
Argument | Description |
input (Tensor) | It represents an input tensor. |
other (Tensor) | It represents the other tensor or scalar with which to perform the XOR operation. |
out (Tensor, optional) | It can be used to store the output result. |
Element-wise XOR operation
import torch main_tensor = torch.tensor([1, 2, 3]) # Binary: 001, 010, 011 other_tensor = torch.tensor([2, 3, 1]) # Binary: 010, 011, 001 bitwise_xor_tensor = torch.bitwise_xor(main_tensor, other_tensor) print(bitwise_xor_tensor) # Output: tensor([3, 1, 2]) # Binary: 011, 001, 010
In the above code, the first element of the main_tensor performs an XOR with the first element of other_tensor.
Our input tensor is main_tensor, and it contains three elements: 1, 2, and 3. The binary format of these numbers is 001 101 and 011. The bitwise_xor() method operates on the binary.
Our other_tensor contains elements 2, 3, and 1. The binary of these numbers is 010, 011, and 001.
Therefore, it will operate 001 and 010, and based on the truth table, the output is 011, which corresponds to the integer 3.
The second elements of both tensors are 010 and 011, and the output is 001, which corresponds to the integer 1.
The third elements of both tensors are 011 and 001, and the output is 010, which corresponds to the integer 2.
Boolean Tensor XOR

If both values are either True or False, XOR returns False, but if one of them is True and the other is False, XOR returns True.
import torch tensor_a = torch.tensor([True, False, True, False], dtype=torch.bool) tensor_b = torch.tensor([False, True, True, False], dtype=torch.bool) result = torch.bitwise_xor(tensor_a, tensor_b) print(result) # Output: tensor([ True, True, False, False]
Scalar input

If the first input is a tensor and the other input is a scalar value, it still performs the XOR operation without any issues.
import torch tensor = torch.tensor([1, 2, 3]) # Binary: [001, 010, 011] scalar = 2 # Binary: [010] output = torch.bitwise_xor(tensor, scalar) print(output) # Binary: [011, 000, 001] # Output: tensor([3, 0, 1])That’s all!