The Wayback Machine - https://web.archive.org/web/20240913184250/https://www.geeksforgeeks.org/bitwise-xor-operator-in-programming/
Open In App

Bitwise XOR Operator in Programming

Last Updated : 30 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Bitwise XOR Operator is represented by the caret symbol (^). It is used to perform a bitwise XOR operation on the individual bits of two operands. The XOR operator returns 1 if the corresponding bits in the two operands are different, and 0 if they are the same.

What is Bitwise XOR?

Bitwise XOR (exclusive OR) is a binary operation that takes two equal-length binary representations and performs the logical XOR operation on each pair of corresponding bits. The result in each position is 1 if only one of the two bits is 1 but will be 0 if both are 0 or both are 1.

The truth table for the XOR (exclusive OR) operation is as follows:

ABA XOR B
000
011
101
110

In this table, A and B are the variables, and A XOR B is the expression representing the logical XOR operation. The table shows all possible combinations of truth values for A and B, and the resulting truth value of A XOR B for each combination.

The XOR operation returns 1 (true) if the inputs are different, and 0 (false) if they are the same. This is why the output is 1 for the second and third rows, where A and B have different values, and 0 for the first and fourth rows, where A and B have the same value.

Bitwise XOR operator:

The bitwise XOR operator is represented by the caret symbol (^) in many programming languages, including Python, C, C++, and Java.

result = operand1 ^ operand2;

Bitwise XOR operator in C:

C
#include <stdio.h>

int main()
{
    int a = 10; // 1010 in binary
    int b = 6; // 0110 in binary

    int result = a ^ b; // 1100 in binary

    printf("%d\n", result); // Output: 12

    return 0;
}

Output
12

Bitwise XOR operator in C++:

C++
#include <iostream>
using namespace std;

int main()
{
    int a = 10; // 1010 in binary
    int b = 6; // 0110 in binary

    int result = a ^ b; // 1100 in binary

    cout << result << endl; // Output: 12

    return 0;
}

Output
12

Bitwise XOR operator in Java:

Java
import java.io.*;
class GFG {
    public static void main(String[] args)
    {
        int a = 10; // 1010 in binary
        int b = 6; // 0110 in binary

        int result = a ^ b; // 1100 in binary

        System.out.println(result); // Output: 12
    }
}

Output
12

Bitwise XOR operator in Python:

Python
a = 10  # 1010 in binary
b = 6   # 0110 in binary

result = a ^ b  # 1100 in binary

print(result)  # Output: 12

Output
12

Bitwise XOR operator in C#:

C#
using System;

class MainClass {
    public static void Main(string[] args)
    {
        int a = 10; // 1010 in binary
        int b = 6; // 0110 in binary

        int result = a ^ b; // 1100 in binary

        Console.WriteLine(result); // Output: 12
    }
}

Output
12

Bitwise XOR operator in Javascript:

JavaScript
let a = 10;  // 1010 in binary
let b = 6;   // 0110 in binary

let result = a ^ b;  // 1100 in binary

console.log(result);  // Output: 12

Output
12

Use Cases of Bitwise XOR Operator:

The bitwise XOR operator (^) has several use cases in programming:

  • Flipping individual bits: The XOR operator can be used to flip individual bits in a number. For example, x ^ 1 will flip the least significant bit of x.
  • Swapping two variables without a temporary variable: The XOR operator can be used to swap the values of two variables without using a temporary variable. For example, a ^= b; b ^= a; a ^= b; will swap the values of a and b.
  • Checking if two numbers have opposite signs: The XOR operator can be used to check if two numbers have opposite signs. For example, (x ^ y) < 0 will return true if x and y have opposite signs.
  • Implementing simple encryption algorithms: The XOR operator can be used to implement simple encryption algorithms. For example, x ^ key will encrypt x using key, and x ^ key ^ key will decrypt x using key.
  • Detecting changes in data: The XOR operator can be used to detect changes in data. For example, x ^ y will return 0 if x and y are the same, and a non-zero value if they are different.

Applications of Bitwise XOR Operator:

Here are some applications of the bitwise XOR operator:

  • Error detection and correction: XOR operations are used in error detection and correction codes like CRC (Cyclic Redundancy Check) and Hamming codes. By XORing the data with a known pattern, errors in transmission can be detected and corrected.
  • Random number generation: XOR operations can be used in pseudo-random number generation algorithms. By XORing a number with itself and a shifting pattern, a sequence of seemingly random numbers can be generated.
  • Parity checking: XOR operations are used in parity checking to determine if the number of bits set to 1 in a binary word is odd or even. This is often used in computer memory systems to detect errors.
  • Image processing: XOR operations can be used in image processing to perform operations like image blending, edge detection, and watermarking.
  • Digital signal processing: XOR operations are used in digital signal processing algorithms like Fast Fourier Transform (FFT) and convolution to perform operations on digital signals.
  • Cryptographic hash functions: XOR operations are used in cryptographic hash functions like MD5 and SHA-1 to create a unique hash value for a given input.
  • Network protocols: XOR operations are used in network protocols like TCP and UDP to calculate checksums for data packets to ensure data integrity during transmission.


Similar Reads

Bitwise AND operator in Programming
In programming, Bitwise Operators play a crucial role in manipulating individual bits of data. One of the fundamental bitwise operators is the Bitwise AND operator (&amp;). In this article, we'll dive deep into what is Bitwise AND operator, its syntax, properties, applications, and optimization techniques, and conclude with its significance in prog
6 min read
Bitwise OR Operator (|) in Programming
In programming, Bitwise Operators play a crucial role in manipulating individual bits of data. One of the fundamental bitwise operators is the Bitwise OR operator (|). In this article, we’ll discuss the Bitwise OR operator, its syntax, properties, applications, and optimization techniques, and conclude with its significance in programming. Table of
5 min read
Bitwise Left Shift(&lt;&lt;) Operator in Programming
Bitwise operators play a significant role in manipulating individual bits within binary data. Among these operators, the Bitwise Left Shift (&lt;&lt;) operator is used for shifting the bits of a number to the left by a specified number of positions. In this blog post, we'll explore the definition, syntax, examples, and optimization techniques assoc
5 min read
Difference between Operator Precedence and Operator Associativity
In programming, operators are used to perform various operations on data. Understanding how operators interact with each other is crucial for writing correct and efficient code. In this article, we will explore the two most important concepts which are Operator Precedence and Operator Associativity. Operator Precedence:Operator precedence determine
3 min read
Operator Precedence and Associativity in Programming
We have many types of operators in a programming language. Operators serve many purposes. But when we have many operators within the same statement, Operator Precedence and Associativity come into the picture. They define which operator should be taken into account first. It is similar to the BODMAS rule we have learned in our school mathematics. I
3 min read
Operator Overloading in Programming
Operator Overloading is a feature in some programming languages used to redefine or "overload" the standard behavior of operators (such as +, -, *, etc.) to work with user-defined data types. This is useful when working with objects of custom classes. In this article, we will learn about the basics of Operator overloading and its implementation in
4 min read
Operator Precedence in Programming
Operator Precedence, also known as operator hierarchy, is a set of rules that controls the order in which operations are performed in an expression without parentheses. It is a fundamental concept in programming languages and is crucial for writing correct and efficient code. Table of Content What is Operator Precedence?Operator Precedence in Arith
13 min read
Right Shift Operator (>>) in Programming
Right shift operator (&gt;&gt;), commonly found in programming languages, including C, C++, Java, and others, is used to shift the bits of a number to the right by a specified number of positions. Each shift moves all bits in the operand to the right by the number of positions indicated by the right operand. Table of Content Right Shift Operator (
15+ min read
Conditional Operator in Programming
Conditional Operator, often referred to as the ternary operator, is a concise way to express a conditional (if-else) statement in many programming languages. It is represented by the "?" symbol and is sometimes called the ternary operator because it takes three operands. Table of Content Syntax of Conditional OperatorsConditional Operator in CCondi
9 min read
Pre Increment and Post Increment Operator in Programming
Pre Increment Operator and Post Increment Operator are the two ways of using the Increment operator to increment the value of a variable by 1. They can be used with numeric data values such as int, float, double, etc. Pre-increment and Post-increment perform similar tasks with minor distinctions. In this article, we will discuss the pre-increment a
6 min read
Ternary Operator in Programming
The Ternary Operator is similar to the if-else statement as it follows the same algorithm as of if-else statement but the ternary operator takes less space and helps to write the if-else statements in the shortest way possible. It is known as the ternary operator because it operates on three operands. Table of Content What is a Ternary Operator?Syn
4 min read
Logical OR operator in Programming
In programming, Logical operators play a crucial role in manipulating individual bits of data. One of the fundamental logical operators is the Logical OR operator(||).In this article, we’ll dive deep into what is a Logical OR operator, its syntax, properties, applications, and optimization techniques, and conclude with its significance in programmi
5 min read
Logical AND operator in Programming
In programming, Logical operators play a crucial role in manipulating individual data. One of the fundamental logical operators is the Logical AND operator(&amp;&amp;).In this article, we’ll discuss what is a Logical AND operator, its syntax, properties, applications, and optimization techniques, and conclude with its significance in programming. T
5 min read
Logical NOT Operator in Programming
In programming, Logical operators play a crucial role in manipulating data. One of the fundamental logical operators is the Logical NOT operator(!).In this article, we’ll discuss the Logical NOT operator, its syntax, properties, applications, and optimization techniques, and conclude with its significance in programming. Table of Content What is a
5 min read
Pre and Post Decrement Operator in Programming
Pre-decrement and post-decrement are the two ways of using the decrement operator to decrement the value of a variable by 1. They can be used with numeric data type values such as int, float, double, etc. Pre-decrement and Post-decrement perform similar tasks with minor distinctions. Table of Content What is a Pre-Decrement Operator?What is a Post-
5 min read
Modulus Operator in Programming
The modulus operator, often represented by the symbol '%', is a fundamental arithmetic operator used in programming languages to find the remainder of a division operation between two numbers. It returns the remainder of dividing the first operand by the second operand. Table of Content What is the Modulus Operator? Basic Syntax of Modulus Operator
5 min read
Operator Associativity in Programming
Operator associative refers to the order in which operators of the same precedence are used in a word. In a programming language, it is important to understand the interactions between operators to properly define and test expressions. In this article, we will discuss operator associativity in programming. Table of Content Operator Associativity in
14 min read
Complete Reference for Bitwise Operators in Programming/Coding
There exists no programming language that doesn't use Bit Manipulations. Bit manipulation is all about these bitwise operations. They improve the efficiency of programs by being primitive, fast actions. There are different bitwise operations used in bit manipulation. These Bitwise Operators operate on the individual bits of the bit patterns. Bit op
13 min read
Program for Bitwise Operators in C, C++, Java, Python, C# & JavaScript
Bitwise operators are fundamental operators used in computer programming for manipulating individual data bits. They operate at the binary level, performing operations on binary data representations. These operators are commonly used in low-level programming, such as device drivers, embedded systems, and cryptography, where manipulation at the bit
9 min read
Which Programming Language to Choose?
One of the most annoying question today is which programming language should be chosen for the sake of education/career or anything. Answer for this question to many programmers ends up with C or C++, or mostly Java but why C? why C++? Why Java?. Today many software exists, to solve a problem but also to interfere with another software. nowadays in
4 min read
Hello World Program : First program while learning Programming
In this article, I'll show you how to create your first Hello World computer program in various languages. Along with the program, comments are provided to help you better understand the terms and keywords used in theLearning program. Programming can be simplified as follows: Write the program in a text editor and save it with the correct extension
6 min read
What are Objects in Programming?
In object-oriented programming (OOP), objects are the basic entities that actually exists in the memory. Each object is based on a blueprint of attributes and behaviours (variables and functions) defined as Class. The basic purpose of a Class is to identify the common attributes and behaviours and group them as an entity that can be reused again an
2 min read
If-Then-___ Trio in Programming
Learning to code is a bit like discovering magic spells, and one trio of spells you'll encounter often is called "If-Then-___." These spells help your code make decisions like a wizard choosing the right spell for a particular situation. Table of Content If-Then-ElseIf-Then-TernaryIf-Then-ThrowIf-Then-Async/AwaitWhen to use each If-Then-___ Trio in
2 min read
What is a Code in Programming?
In programming, "code" refers to a set of instructions or commands written in a programming language that a computer can understand and execute. In this article, we will learn about the basics of Code, types of Codes and difference between Code, Program, Script, etc. Table of Content What is Code?Code in Programming Language:Types of CodeDifferent
10 min read
Most Famous Online IDE for Programming
Integrated Development Environment (IDE) provides crucial tools for software development. IDE provides developers with tools like code editor, compiler, interpreter, debugger, code library, and testing tools that help developers in writing, compiling, debugging, and testing the code. Without IDE developers have to do every task individually. IDE in
5 min read
Basic Programming Problems
Learn Programming – How To Code In the world of programming, mastering the fundamentals is key to becoming a proficient developer. In this article, we will explore a variety of basic programming problems that are essential for every aspiring coder to understand. By delving into these foundational challenges, you will gain valuable insights into pro
4 min read
Basics of Computer Programming For Beginners
Be it any programming language in which you want to grow your career, It's very important to learn the fundamentals first. Before having a good command over the basic concepts of programming, you cannot imagine the growth in that particular career. Hence, this article will talk about all the basic concepts of programming. Also, if you're a beginner
7 min read
Programming vs Coding - A Short Comparison Between Both
The terms "programming" and "coding" are often used interchangeably, but they can have slightly different nuances in meaning. Programming is a broader and more encompassing term that involves various activities throughout the software development lifecycle, while coding is a specific task within programming that deals with writing the actual lines
3 min read
Top 10 Programming Tips For Beginners
Whether you are a novice or have just started to learn programming, there are key tips that can significantly enhance your learning experience. In this blog post, we'll explore the top 10 programming tips for beginners that can help you build a strong foundation and navigate the complexities of coding with confidence. Top 10 Programming Tips For Be
8 min read
7 Ways To Make Programming More Interesting For Beginners
How to make programming more interesting, exciting, and fun...?? It is indeed the common query of almost every programmer, especially the beginner ones. Let's find an effective solution to it in this article.   It’s the 21st day of June and the year is 1948. It is a pleasant summer day for many but for mathematician and computer engineer Tom Kilbur
7 min read
Article Tags :