How do you get the xor of two numbers in python?

How do you get the xor of two numbers in python?

Python bitwise operators are used to perform bitwise calculations on integers. First, the integers are converted into binary format, and then operations are performed bit by bit, hence the name of the bitwise operators.

Python bitwise operators work on integers only, and the final output is returned in the decimal format. Python bitwise operators are also called binary operators.

XOR in Python is known as “exclusive or”, which compares two binary numbers bitwise. If both bits are the same, the XOR operator outputs 0. If both bits are different, the XOR operator outputs 1.

The Bitwise XOR sets the input bits to 1 if either, but not both, of the analogous bits in the two operands is 1.

Use the XOR operator ^ between two values to perform bitwise “exclusive or” on their binary representations.

For example, when used between two integers, the XOR operator returns an integer.

output = 19 ^ 21

print(output)

Output

6

We have used the XOR operator between two integers. When used between two integers, the XOR operator returns an integer.

When performing XOR on two booleans, True is treated as 1, and False is treated as 0. Thus, XOR between two booleans returns a boolean.

result = True ^ False

print(result)

Output

True

Let’s compare two False values.

result = False ^ False

print(result)

Output

False

Let’s compare two True values.

result = True ^ True

print(result)

Output

False

From the above code example, you can see that if two True or False values are compared, it returns False, but if two different values are compared, it will return True.

More Examples

See the following code.

result = bin(0b1111 ^ 0b1111)

print(result)

Output

0b0

Let’s see how to swap integers without a temporary variable using XOR.

a = 21
b = 19

print('The value of a is: ', a)
print('The value of b is: ', b)

a ^= b
b ^= a
a ^= b

print('After swapping: ')
print('The value of a is: ', a)
print('The value of b is: ', b)

Output

The value of a is:  21
The value of b is:  19
After swapping:
The value of a is:  19
The value of b is:  21

That’s it for this tutorial.

See also

Python And

Given two integers, find XOR of them without using the XOR operator, i.e., without using ^ in C/C++.

Examples :  

Input:  x = 1, y = 2
Output: 3

Input:  x = 3, y = 5
Output: 6

A Simple Solution is to traverse all bits one by one. For every pair of bits, check if both are the same, set the corresponding bit like 0 in output, otherwise set it as 1. 

C++

#include <iostream>

using namespace std;

int myXOR(int x, int y)

{

    int res = 0;

    for (int i = 31; i >= 0; i--)                    

    {

       bool b1 = x & (1 << i);

       bool b2 = y & (1 << i);

        bool xoredBit = (b1 & b2) ? 0 : (b1 | b2);         

        res <<= 1;

        res |= xoredBit;

    }

    return res;

}

int main()

{

   int x = 3, y = 5;

   cout << "XOR is " << myXOR(x, y);

   return 0;

}

C

#include <stdio.h>

#include <stdbool.h> //to use bool

int myXOR(int x, int y)

{

    int res = 0;

    for (int i = 31; i >= 0; i--)

    {

        bool b1 = x & (1 << i);

        bool b2 = y & (1 << i);

        bool xoredBit = (b1 & b2) ? 0 : (b1 | b2);

        res <<= 1;

        res |= xoredBit;

    }

    return res;

}

int main()

{

    int x = 3, y = 5;

    printf("XOR is %d\n", myXOR(x, y));

    return 0;

}

Java

import java.io.*;

class GFG{

static int myXOR(int x, int y)

{

    int res = 0;

    for(int i = 31; i >= 0; i--)                    

    {

        int b1 = ((x & (1 << i)) == 0 ) ? 0 : 1

        int b2 = ((y & (1 << i)) == 0 ) ? 0 : 1

        int xoredBit = ((b1 & b2) != 0) ? 0 : (b1 | b2);         

        res <<= 1;

        res |= xoredBit;

    }

    return res;

}

public static void main (String[] args)

{

    int x = 3, y = 5;

    System.out.println("XOR is " + myXOR(x, y));

}

}

Python3

def myXOR(x, y):

    res = 0

    for i in range(31, -1, -1):

        b1 = x & (1 << i)

        b2 = y & (1 << i)

        b1 = min(b1, 1)

        b2 = min(b2, 1)

        xoredBit = 0

        if (b1 & b2):

            xoredBit = 0

        else:

            xoredBit = (b1 | b2)

        res <<= 1;

        res |= xoredBit

    return res

x = 3

y = 5

print("XOR is", myXOR(x, y))

C#

using System;

class GFG{

static int myXOR(int x,

                 int y)

{   

  int res = 0;

  for(int i = 31; i >= 0; i--)                    

  {

    int b1 = ((x & (1 << i)) == 0 ) ?

               0 : 1; 

    int b2 = ((y & (1 << i)) == 0 ) ?

               0 : 1; 

    int xoredBit = ((b1 & b2) != 0) ?

                     0 : (b1 | b2);         

    res <<= 1;

    res |= xoredBit;

  }

  return res;

}

public static void Main(String[] args)

{

  int x = 3, y = 5;

  Console.WriteLine("XOR is " +

                     myXOR(x, y));

}

}

Javascript

<script>

function myXOR(x, y)

{

    let res = 0;

    for (let i = 31; i >= 0; i--)                    

    {

      let b1 = ((x & (1 << i)) == 0 ) ? 0 : 1; 

      let b2 = ((y & (1 << i)) == 0 ) ? 0 : 1; 

        let xoredBit = (b1 & b2) ? 0 : (b1 | b2);        

        res <<= 1;

        res |= xoredBit;

    }

    return res;

}

let x = 3, y = 5;

document.write("XOR is " + myXOR(x, y));

</script>

Time Complexity: O(num), where num is the number of bits in the maximum of the two numbers.

Space Complexity: O(1)

Thanks to Utkarsh Trivedi for suggesting this solution.
 
A Better Solution can find XOR without using a loop. 
1) Find bitwise OR of x and y (Result has set bits where either x has set or y has set bit). OR of x = 3 (011) and y = 5 (101) is 7 (111)
2) To remove extra set bits find places where both x and y have set bits. The value of the expression “~x | ~y” has 0 bits wherever x and y both have set bits.
3) bitwise AND of “(x | y)” and “~x | ~y” produces the required result.

Below is the implementation. 

C++

#include <iostream>

using namespace std;

int myXOR(int x, int y)

{

   return (x | y) & (~x | ~y);

}

int main()

{

   int x = 3, y = 5;

   cout << "XOR is " << myXOR(x, y);

   return 0;

}

Java

import java.io.*;

class GFG

{

static int myXOR(int x, int y)

{

    return (x | y) &

           (~x | ~y);

}

public static void main (String[] args)

{

    int x = 3, y = 5;

    System.out.println("XOR is "+

                      (myXOR(x, y)));

}

}

Python3

def myXOR(x, y):

    return ((x | y) &

            (~x | ~y))

x = 3

y = 5

print("XOR is" ,

       myXOR(x, y))

C#

using System;

class GFG

{

static int myXOR(int x, int y)

{

    return (x | y) &

           (~x | ~y);

}

static public void Main ()

{

    int x = 3, y = 5;

    Console.WriteLine("XOR is "+

                     (myXOR(x, y)));

}

}

PHP

<?php

function myXOR($x, $y)

{

    return ($x | $y) & (~$x | ~$y);

}

$x = 3;

$y = 5;

echo "XOR is " , myXOR($x, $y);

?>

Javascript

<script>

function myXOR(x, y)

{

   return (x | y) & (~x | ~y);

}

   let x = 3, y = 5;

   document.write("XOR is " + myXOR(x, y));

</script>

Time Complexity: O(1)

Space Complexity: O(1)

Thanks to jitu_the_best for suggesting this solution. 

Alternate Solution : 

C++

#include <iostream>

using namespace std;

int myXOR(int x, int y)

{

   return (x & (~y)) | ((~x )& y);

}

int main()

{

   int x = 3, y = 5;

   cout << "XOR is " << myXOR(x, y);

   return 0;

}

Java

import java.io.*;

class GFG

{

static int myXOR(int x, int y)

{

return (x & (~y)) | ((~x )& y);

}

public static void main (String[] args)

{

int x = 3, y = 5;

System.out.println("XOR is "+

                      (myXOR(x, y)));

}

}

Python3

def myXOR(x, y):

    return (x & (~y)) | ((~x )& y)

x = 3

y = 5

print("XOR is" ,

    myXOR(x, y))

C#

using System;

class GFG{

static int myXOR(int x, int y)

{

    return (x & (~y)) | ((~x )& y);

}

public static void Main()

{

    int x = 3, y = 5;

    Console.WriteLine("XOR is " +myXOR(x, y));

}

}

Javascript

<script>

function myXOR(x, y)

{

   return (x & (~y)) | ((~x ) & y);

}

let x = 3, y = 5;

document.write("XOR is " + myXOR(x, y));

</script>

Time Complexity: O(1)

Space Complexity: O(1)

Another Solution: we can simply use one of the properties of the XOR bitwise operator i.e. a+b = a^b + 2*(a&b), with the help of this we can do the same for an operator variant also.

C++14

#include <iostream>

using namespace std;

int XOR(int x, int y) { return (x + y - (2 * (x & y))); }

int main()

{

    int x = 3, y = 5;

    cout << XOR(x, y) << endl;

    return 0;

}

Java

class GFG {

    static int XOR(int x, int y) {

        return (x + y - (2 * (x & y)));

    }

    public static void main(String[] args) {

        int x = 3, y = 5;

        System.out.print(XOR(x, y) + "\n");

    }

}

Python3

def XOR(x, y):

    return (x+y - (2*(x & y)))

x = 3

y = 5

print("XOR of",x,'&',y,'is:',

      XOR(x, y))

C#

using System;

class GFG{

static int XOR(int x, int y)

{

    return(x + y - (2 * (x & y)));

}

public static void Main(String[] args)

{

    int x = 3, y = 5;

    Console.Write(XOR(x, y) + "\n");

}

}

Javascript

<script>

   function XOR(x , y) {

        return (x + y - (2 * (x & y)));

    }

        var x = 3, y = 5;

        document.write(XOR(x, y) + "\n");

</script>

Time Complexity: O(1) i.e. simple calculation of arithmetic and bitwise operator.

Auxiliary Space: O(1)

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


What is XOR AND OR in Python?

Python XOR Vs. Python OR Python XOR is, also known as “exclusive or”, compares two binary numbers bitwise if two bits are identical XOR outputs as False. True, and when two bits are different, then XOR outputs as 1. With the Boolean OR operator, you can connect two Boolean expressions into one compound expression.

How to get XOR of booleans and integers in Python?

The xor () method of the operator module of Python can also be used to get XOR of Booleans and integers. The functionality of xor () method in Python is the same as the ^ operator. It also performs bitwise XOR operation on integers and XOR operation on the booleans.

How to find the XOR result of the given two numbers?

Below are the ways to find the XOR result of the given two numbers in Python: Create a function XOR_result () which accepts the given two numbers as the arguments and returns the XOR result of the given first and second numbers. Inside the XOR_result() function.

What is the XOR of 0b011 and 0b101 in Python?

3 in binary is 0b11 and 5 is 0b101, so the XOR of 0b011 and 0b101 will be 0b110, which is 6 in decimal. We can implement a user-defined xor () method using logical operators in Python.

How do you find the XOR of two numbers in Python?

Use the XOR operator ^ between two values to perform bitwise “exclusive or” on their binary representations..
For example, when used between two integers, the XOR operator returns an integer. ... .
When performing XOR on two booleans, True is treated as 1, and False is treated as 0. ... .
Let's compare two False values..

How does Python calculate XOR value?

1- Initialize the result as 0. 1- Traverse all numbers from 1 to n..
Find the remainder of n by moduling it with 4..
If rem = 0, then XOR will be same as n..
If rem = 1, then XOR will be 1..
If rem = 2, then XOR will be n+1..
If rem = 3 ,then XOR will be 0..

How do I get XOR 2 numbers?

To find the XOR of two numbers, follow these instructions:.
Convert the numbers into the binary representation..
Compare the corresponding bits of the two numbers..
If only one of the input bits is true (1), the output is true (1). Otherwise, the output is false (0)..

How do you find the XOR of a list in Python?

Method #1 : Using reduce() + lambda + “^” operator We can employ reduce() to accumulate the result of XOR logic specified by the lambda function.