• TutorialKart
  • SAP Tutorials
  • Salesforce Admin
  • Salesforce Developer
  • Visualforce
  • Informatica
  • Kafka Tutorial
  • Spark Tutorial
  • Tomcat Tutorial
  • Python Tkinter

Programming

  • Bash Script
  • Julia Tutorial
  • CouchDB Tutorial
  • MongoDB Tutorial
  • PostgreSQL Tutorial
  • Android Compose
  • Flutter Tutorial
  • Kotlin Android

Web & Server

  • Selenium Java
  • C++ Tutorials
  • C++ Tutorial
  • C++ Hello World Program
  • C++ Comments
  • C++ Variables
  • Print datatype of variable
  • C++ If Else
  • Addition Operator
  • Subtraction Operator
  • Multiplication Operator
  • Division Operator
  • Modulus Operator
  • Increment Operator
  • Decrement Operator
  • Simple Assignment
  • Addition Assignment
  • Subtraction Assignment
  • Multiplication Assignment
  • Division Assignment
  • Remainder Assignment
  • Bitwise AND Assignment
  • Bitwise OR Assignment
  • Bitwise XOR Assignment
  • Left Shift Assignment
  • Right Shift Assignment
  • Bitwise AND
  • Bitwise XOR
  • Bitwise Complement
  • Bitwise Left shift
  • Bitwise Right shift
  • ADVERTISEMENT
  • Logical AND
  • Logical NOT
  • Not Equal to
  • Greater than
  • Greater than or Equal to
  • Less than or Equal to
  • Ternary Operator
  • Do-while loop
  • Infinite While loop
  • Infinite For loop
  • C++ Recursion
  • Create empty string
  • String length
  • String comparison
  • Get character at specific index
  • Get first character
  • Get last character
  • Find index of substring
  • Iterate over characters
  • Print unique characters
  • Check if strings are equal
  • Append string
  • Concatenate strings
  • String reverse
  • String replace
  • Swap strings
  • Convert string to uppercase
  • Convert string to lowercase
  • Append character at end of string
  • Append character to beginning of string
  • Insert character at specific index
  • Remove last character
  • Replace specific character
  • Convert string to integer
  • Convert integer to string
  • Convert string to char array
  • Convert char array to string
  • Initialize array
  • Array length
  • Print array
  • Loop through array
  • Basic array operations
  • Array of objects
  • Array of arrays
  • Convert array to vector
  • Sum of elements in array
  • Average of elements in array
  • Find largest number in array
  • Find smallest number in array
  • Sort integer array
  • Find string with least length in array
  • Create an empty vector
  • Create vector of specific size
  • Create vector with initial values
  • Copy a vector to another
  • Vector length or size
  • Vector of vectors
  • Vector print elements
  • Vector iterate using For loop
  • Vector iterate using While loop
  • Vector Foreach
  • Get reference to element at specific index
  • Check if vector is empty
  • Check if vectors are equal
  • Check if vector contains element
  • Update/Transform
  • Add element(s) to vector
  • Append element to vector
  • Append vector
  • Insert element at the beginning of vector
  • Remove first element from vector
  • Remove last element from vector
  • Remove element at specific index from vector
  • Remove duplicates from vector
  • Remove elements from vector based on condition
  • Resize vector
  • Swap elements of two vectors
  • Remove all elements from vector
  • Reverse a vector
  • Sort a vector
  • Conversions
  • Convert vector to map
  • Join vector elements to a string
  • Filter even numbers in vector
  • Filter odd numbers in vector
  • Get unique elements of a vector
  • Remove empty strings from vector
  • Sort integer vector in ascending order
  • Sort integer vector in descending order
  • Sort string vector based on length
  • Sort string vector lexicographically
  • Split vector into two equal halves
  • Declare tuple
  • Initialise tuple
  • Swap tuples
  • Unpack tuple elements into variables
  • Concatenate tuples
  • Constructor
  • Copy constructor
  • Virtual destructor
  • Friend class
  • Friend function
  • Inheritance
  • Multiple inheritance
  • Virtual inheritance
  • Function overloading
  • Operator overloading
  • Function overriding
  • C++ Try Catch
  • Math acos()
  • Math acosh()
  • Math asin()
  • Math asinh()
  • Math atan()
  • Math atan2()
  • Math atanh()
  • Math cbrt()
  • Math ceil()
  • Math copysign()
  • Math cosh()
  • Math exp2()
  • Math expm1()
  • Math fabs()
  • Math fdim()
  • Math floor()
  • Math fmax()
  • Math fmin()
  • Math fmod()
  • Math frexp()
  • Math hypot()
  • Math ilogb()
  • Math ldexp()
  • Math llrint()
  • Math llround()
  • Math log10()
  • Math log1p()
  • Math log2()
  • Math logb()
  • Math lrint()
  • Math lround()
  • Math modf()
  • Math nearbyint()
  • Math nextafter()
  • Math nexttoward()
  • Math remainder()
  • Math remquo()
  • Math rint()
  • Math round()
  • Math scalbln()
  • Math scalbn()
  • Math sinh()
  • Math sqrt()
  • Math tanh()
  • Math trunc()
  • Armstrong number
  • Average of three numbers
  • Convert decimal to binary
  • Factorial of a number
  • Factors of a number
  • Fibonacci series
  • Find largest of three numbers
  • Find quotient and remainder
  • HCF/GCD of two numbers
  • Hello World
  • LCM of two numbers
  • Maximum of three numbers
  • Multiply two numbers
  • Sum of two numbers
  • Sum of three numbers
  • Sum of natural numbers
  • Sum of digits in a number
  • Swap two numbers
  • Palindrome number
  • Palindrome string
  • Pattern printing
  • Power of a number
  • Prime number
  • Prime Numbers between two numbers
  • Print number entered by User
  • Reverse a Number
  • Read input from user
  • ❯ C++ Tutorial
  • ❯ C++ Operators
  • ❯ Assignment Operators
  • ❯ Bitwise XOR Assignment

C++ Bitwise XOR Assignment (^=) Operator

In this C++ tutorial, you shall learn about Bitwise XOR Assignment operator, its syntax, and how to use this operator, with examples.

C++ Bitwise XOR Assignment

In C++, Bitwise XOR Assignment Operator is used to compute the Bitwise XOR operation between left and right operands, and assign the result back to left operand.

The syntax to compute bitwise XOR a value of 2 and value in variable x , and assign the result back to x using Bitwise XOR Assignment Operator is

In the following example, we take a variable x with an initial value of 9 , add bitwise XOR it with value of 2 , and assign the result to x , using Bitwise XOR Assignment Operator.

In this C++ Tutorial , we learned about Bitwise XOR Assignment Operator in C++, with examples.

Popular Courses by TutorialKart

App developement, web development, online tools.

O.2 — Bitwise operators

OperatorSymbolFormOperation
left shift<<x << yall bits in x shifted left y bits
right shift>>x >> yall bits in x shifted right y bits
bitwise NOT~~xall bits in x flipped
bitwise AND&x & yeach bit in x AND each bit in y
bitwise OR|x | yeach bit in x OR each bit in y
bitwise XOR^x ^ yeach bit in x XOR each bit in y
OperatorSymbolFormOperation
Left shift assignment<<=x <<= yShift x left by y bits
Right shift assignment>>=x >>= yShift x right by y bits
Bitwise OR assignment|=x |= yAssign x | y to x
Bitwise AND assignment&=x &= yAssign x & y to x
Bitwise XOR assignment^=x ^= yAssign x ^ y to x
  • Java - Home
  • Java - Introduction
  • Java - Syntax
  • Java - Comments
  • Java - Data Types
  • Java - Type Casting
  • Java - Operators
  • Java - Strings
  • Java - Booleans
  • Java - If Else
  • Java - Switch
  • Java - While Loop
  • Java - For Loop
  • Java - Continue Statement
  • Java - Break Statement
  • Java - Label Statement
  • Java - Arrays
  • Java - Methods
  • Java - Exceptions
  • Java - Classes/Objects
  • Java - Constructors
  • Java - Encapsulation
  • Java - Inheritance
  • Java - Polymorphism
  • Java.lang Package
  • Java Utility Package
  • Java - Keywords
  • Java - String Methods
  • Java - Math Methods
  • Java - Data Structures
  • Java - Examples
  • Java - Interview Questions

AlphaCodingSkills

Facebook Page

  • Programming Languages
  • Web Technologies
  • Database Technologies
  • Microsoft Technologies
  • Python Libraries
  • Data Structures
  • Interview Questions
  • PHP & MySQL
  • C++ Standard Library
  • C Standard Library
  • Java Utility Library
  • Java Default Package
  • PHP Function Reference

Java - Bitwise XOR and assignment operator

The Bitwise XOR and assignment operator (^=) assigns the first operand a value equal to the result of Bitwise XOR operation of two operands.

(x ^= y) is equivalent to (x = x ^ y)

The Bitwise XOR operator (^) is a binary operator which takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of corresponding bits. It returns 1 if only one of the bits is 1, else returns 0.

Bit_1Bit_2Bit_1 ^ Bit_2
000
101
011
110

The example below describes how bitwise XOR operator works:

The code of using Bitwise XOR and assignment operator (^=) is given below:

The output of the above code will be:

Example: Swap two numbers without using temporary variable

The bitwise XOR and assignment operator can be used to swap the value of two variables. Consider the example below.

The above code will give the following output:

AlphaCodingSkills Android App

  • Data Structures Tutorial
  • Algorithms Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQLi Tutorial
  • Java Tutorial
  • Scala Tutorial
  • C++ Tutorial
  • C# Tutorial
  • PHP Tutorial
  • MySQL Tutorial
  • SQL Tutorial
  • PHP Function reference
  • C++ - Standard Library
  • Ruby Tutorial
  • Rust Tutorial
  • Swift Tutorial
  • Perl Tutorial
  • HTML Tutorial
  • CSS Tutorial
  • AJAX Tutorial
  • XML Tutorial
  • Online Compilers
  • QuickTables
  • NumPy Tutorial
  • Pandas Tutorial
  • Matplotlib Tutorial
  • SciPy Tutorial
  • Seaborn Tutorial

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript bitwise operations, javascript bitwise operators.

Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shifts left by pushing zeros in from the right and let the leftmost bits fall off
>> Signed right shift Shifts right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
>>> Zero fill right shift Shifts right by pushing zeros in from the left, and let the rightmost bits fall off
Operation Result Same as Result
5 & 1 1 0101 & 0001  0001
5 | 1 5 0101 | 0001  0101
~ 5 10  ~0101  1010
5 << 1 10 0101 << 1  1010
5 ^ 1 4 0101 ^ 0001  0100
5 >> 1 2 0101 >> 1  0010
5 >>> 1 2 0101 >>> 1  0010

JavaScript Uses 32 bits Bitwise Operands

JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers.

Before a bitwise operation is performed, JavaScript converts numbers to 32 bits signed integers.

After the bitwise operation is performed, the result is converted back to 64 bits JavaScript numbers.

The examples above uses 4 bits unsigned binary numbers. Because of this ~ 5 returns 10.

Since JavaScript uses 32 bits signed integers, it will not return 10. It will return -6.

00000000000000000000000000000101 (5)

11111111111111111111111111111010 (~5 = -6)

A signed integer uses the leftmost bit as the minus sign.

Advertisement

JavaScript Bitwise AND

When a bitwise AND is performed on a pair of bits, it returns 1 if both bits are 1.

OperationResult
0 & 00
0 & 10
1 & 00
1 & 11
OperationResult
1111 & 00000000
1111 & 00010001
1111 & 00100010
1111 & 01000100

JavaScript Bitwise OR

When a bitwise OR is performed on a pair of bits, it returns 1 if one of the bits is 1:

OperationResult
0 | 00
0 | 1
1 | 01
1 | 11
OperationResult
1111 | 00001111
1111 | 00011111
1111 | 00101111
1111 | 01001111

JavaScript Bitwise XOR

When a bitwise XOR is performed on a pair of bits, it returns 1 if the bits are different:

OperationResult
0 ^ 00
0 ^ 1
1 ^ 01
1 ^ 1
OperationResult
1111 ^ 00001111
1111 ^ 00011110
1111 ^ 00101101
1111 ^ 01001011

JavaScript Bitwise AND (&)

Bitwise AND returns 1 only if both bits are 1:

DecimalBinary
500000000000000000000000000000101
100000000000000000000000000000001
5 & 100000000000000000000000000000001 (1)

JavaScript Bitwise OR (|)

Bitwise OR returns 1 if one of the bits is 1:

DecimalBinary
500000000000000000000000000000101
100000000000000000000000000000001
5 | 100000000000000000000000000000101 (5)

JavaScript Bitwise XOR (^)

Bitwise XOR returns 1 if the bits are different:

DecimalBinary
500000000000000000000000000000101
100000000000000000000000000000001
5 ^ 100000000000000000000000000000100 (4)

JavaScript Bitwise NOT (~)

DecimalBinary
500000000000000000000000000000101
~511111111111111111111111111111010 (-6)

JavaScript (Zero Fill) Bitwise Left Shift (<<)

This is a zero fill left shift. One or more zero bits are pushed in from the right, and the leftmost bits fall off:

DecimalBinary
500000000000000000000000000000101
5 << 100000000000000000000000000001010 (10)

JavaScript (Sign Preserving) Bitwise Right Shift (>>)

This is a sign preserving right shift. Copies of the leftmost bit are pushed in from the left, and the rightmost bits fall off:

DecimalBinary
-511111111111111111111111111111011
-5 >> 111111111111111111111111111111101 (-3)

JavaScript (Zero Fill) Right Shift (>>>)

This is a zero fill right shift. One or more zero bits are pushed in from the left, and the rightmost bits fall off:

DecimalBinary
500000000000000000000000000000101
5 >>> 100000000000000000000000000000010 (2)

Binary Numbers

Binary numbers with only one bit set are easy to understand:

Binary RepresentationDecimal value
000000000000000000000000000000011
000000000000000000000000000000102
000000000000000000000000000001004
000000000000000000000000000010008
0000000000000000000000000001000016
0000000000000000000000000010000032
0000000000000000000000000100000064

Setting a few more bits reveals the binary pattern:

Binary RepresentationDecimal value
000000000000000000000000000001015 (4 + 1)
0000000000000000000000000000110113 (8 + 4 + 1)
0000000000000000000000000010110145 (32 + 8 + 4 + 1)

JavaScript binary numbers are stored in two's complement format.

This means that a negative number is the bitwise NOT of the number plus 1:

Binary RepresentationDecimal value
000000000000000000000000000001015
11111111111111111111111111111011-5
000000000000000000000000000001106
11111111111111111111111111111010-6
0000000000000000000000000010100040
11111111111111111111111111011000-40

There are only 10 types of people in the world: those who understand binary and those who don't.

Converting Decimal to Binary

Converting binary to decimal.

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c interactively, c introduction.

  • Getting Started with C
  • Your First C Program

C Fundamentals

  • C Variables, Constants and Literals
  • C Data Types
  • C Input Output (I/O)

C Programming Operators

C Flow Control

  • C if...else Statement
  • C while and do...while Loop
  • C break and continue
  • C switch Statement
  • C goto Statement
  • C Functions
  • C User-defined functions
  • Types of User-defined Functions in C Programming
  • C Recursion
  • C Storage Class

C Programming Arrays

  • C Multidimensional Arrays
  • Pass arrays to a function in C

C Programming Pointers

  • Relationship Between Arrays and Pointers
  • C Pass Addresses and Pointers
  • C Dynamic Memory Allocation
  • C Array and Pointer Examples
  • C Programming Strings
  • String Manipulations In C Programming Using Library Functions
  • String Examples in C Programming

C Structure and Union

  • C structs and Pointers
  • C Structure and Function

C Programming Files

  • C File Handling
  • C Files Examples

C Additional Topics

  • C Keywords and Identifiers

C Precedence And Associativity Of Operators

  • C Bitwise Operators
  • C Preprocessor and Macros
  • C Standard Library Functions

C Tutorials

  • Convert Binary Number to Decimal and vice-versa
  • Convert Binary Number to Octal and vice-versa
  • Make a Simple Calculator Using switch...case

Bitwise Operators in C Programming

In the arithmetic-logic unit (which is within the CPU), mathematical operations like: addition, subtraction, multiplication and division are done in bit-level. To perform bit-level operations in C programming, bitwise operators are used.

Operators Meaning of operators
&
|
^
~
>>

Bitwise AND Operator &

The output of bitwise AND is 1 if the corresponding bits of two operands is 1 . If either bit of an operand is 0 , the result of corresponding bit is evaluated to 0 .

In C Programming, the bitwise AND operator is denoted by & .

Let us suppose the bitwise AND operation of two integers 12 and 25 .

Example 1: Bitwise AND

Bitwise or operator |.

The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1 . In C Programming, bitwise OR operator is denoted by | .

Example 2: Bitwise OR

Bitwise xor (exclusive or) operator ^.

The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. It is denoted by ^ .

Example 3: Bitwise XOR

Bitwise complement operator ~.

Bitwise complement operator is a unary operator (works on only one operand). It changes 1 to 0 and 0 to 1 . It is denoted by ~ .

Twist in Bitwise Complement Operator in C Programming

The bitwise complement of 35 ( ~35 ) is -36 instead of 220 , but why?

For any integer n , bitwise complement of n will be -(n + 1) . To understand this, you should have the knowledge of 2's complement.

2's Complement

Two's complement is an operation on binary numbers. The 2's complement of a number is equal to the complement of that number plus 1. For example:

The bitwise complement of 35 is 220 (in decimal). The 2's complement of 220 is -36 . Hence, the output is -36 instead of 220 .

Bitwise Complement of Any Number N is -(N+1). Here's how:

Example 4: Bitwise complement

Shift operators in c programming.

There are two shift operators in C programming:

  • Right shift operator
  • Left shift operator.

Right Shift Operator

Right shift operator shifts all bits towards right by certain number of specified bits. It is denoted by >> .

Left Shift Operator

Left shift operator shifts all bits towards left by a certain number of specified bits. The bit positions that have been vacated by the left shift operator are filled with 0 . The symbol of the left shift operator is << .

Example #5: Shift Operators

Table of contents.

  • Bitwise AND
  • Bitwise XOR
  • Bitwise complement
  • Shift right

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

C Ternary Operator

  • Skip to main content
  • Select language
  • Skip to search
  • Assignment operators

An assignment operator assigns a value to its left operand based on the value of its right operand.

The basic assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x . The other assignment operators are usually shorthand for standard operations, as shown in the following definitions and examples.

Name Shorthand operator Meaning

Simple assignment operator which assigns a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables. See the example.

Addition assignment

The addition assignment operator adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible. See the addition operator for more details.

Subtraction assignment

The subtraction assignment operator subtracts the value of the right operand from a variable and assigns the result to the variable. See the subtraction operator for more details.

Multiplication assignment

The multiplication assignment operator multiplies a variable by the value of the right operand and assigns the result to the variable. See the multiplication operator for more details.

Division assignment

The division assignment operator divides a variable by the value of the right operand and assigns the result to the variable. See the division operator for more details.

Remainder assignment

The remainder assignment operator divides a variable by the value of the right operand and assigns the remainder to the variable. See the remainder operator for more details.

Exponentiation assignment

This is an experimental technology, part of the ECMAScript 2016 (ES7) proposal. Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes.

The exponentiation assignment operator evaluates to the result of raising first operand to the power second operand. See the exponentiation operator for more details.

Left shift assignment

The left shift assignment operator moves the specified amount of bits to the left and assigns the result to the variable. See the left shift operator for more details.

Right shift assignment

The right shift assignment operator moves the specified amount of bits to the right and assigns the result to the variable. See the right shift operator for more details.

Unsigned right shift assignment

The unsigned right shift assignment operator moves the specified amount of bits to the right and assigns the result to the variable. See the unsigned right shift operator for more details.

Bitwise AND assignment

The bitwise AND assignment operator uses the binary representation of both operands, does a bitwise AND operation on them and assigns the result to the variable. See the bitwise AND operator for more details.

Bitwise XOR assignment

The bitwise XOR assignment operator uses the binary representation of both operands, does a bitwise XOR operation on them and assigns the result to the variable. See the bitwise XOR operator for more details.

Bitwise OR assignment

The bitwise OR assignment operator uses the binary representation of both operands, does a bitwise OR operation on them and assigns the result to the variable. See the bitwise OR operator for more details.

Left operand with another assignment operator

In unusual situations, the assignment operator (e.g. x += y ) is not identical to the meaning expression (here x = x + y ). When the left operand of an assignment operator itself contains an assignment operator, the left operand is evaluated only once. For example:

Specifications

Specification Status Comment
Draft  
Standard  
Standard  
Standard Initial definition.

Browser compatibility

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)
  • Arithmetic operators

Document Tags and Contributors

  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Iterators and generators
  • Meta programming
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • ReferenceError
  • SIMD.Bool16x8
  • SIMD.Bool32x4
  • SIMD.Bool64x2
  • SIMD.Bool8x16
  • SIMD.Float32x4
  • SIMD.Float64x2
  • SIMD.Int16x8
  • SIMD.Int32x4
  • SIMD.Int8x16
  • SIMD.Uint16x8
  • SIMD.Uint32x4
  • SIMD.Uint8x16
  • SharedArrayBuffer
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Array comprehensions
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Conditional (ternary) Operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Operator precedence
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Legacy generator function
  • async function
  • for each...in
  • function declaration
  • try...catch
  • Arguments object
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • constructor
  • element loaded from a different domain for which you violated the same-origin policy.">Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: invalid date
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: More arguments needed
  • TypeError: can't access dead object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cyclic object value
  • TypeError: invalid 'in' operand "x"
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 2015 support in Mozilla
  • ECMAScript 5 support in Mozilla
  • ECMAScript Next support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project
  • Java Course
  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot

Bitwise Operators in Java

Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Here are a few types: 

  • Arithmetic Operators
  • Unary Operators
  • Assignment Operator
  • Relational Operators
  • Logical Operators
  • Ternary Operator
  • Bitwise Operators
  • Shift Operators

This article explains all that one needs to know regarding Bitwise Operators. 

Bitwise operators are used to performing the manipulation of individual bits of a number. They can be used with any integral type (char, short, int, etc.). They are used when performing update and query operations of the Binary indexed trees. 

Now let’s look at each one of the bitwise operators in Java: 

1. Bitwise OR (|) 

This operator is a binary operator, denoted by ‘|’. It returns bit by bit OR of input values, i.e., if either of the bits is 1, it gives 1, else it shows 0. 

2. Bitwise AND (&)

This operator is a binary operator, denoted by ‘&.’ It returns bit by bit AND of input values, i.e., if both bits are 1, it gives 1, else it shows 0. 

3. Bitwise XOR (^) 

This operator is a binary operator, denoted by ‘^.’ It returns bit by bit XOR of input values, i.e., if corresponding bits are different, it gives 1, else it shows 0. 

4. Bitwise Complement (~)

This operator is a unary operator, denoted by ‘~.’ It returns the one’s complement representation of the input value, i.e., with all bits inverted, which means it makes every 0 to 1, and every 1 to 0. 

Note: Compiler will give 2’s complement of that number, i.e., 2’s complement of 10 will be -6.

Auxiliary space:O(1) 

Time complexity:O(1) 

Bit-Shift Operators (Shift Operators) 

Shift operators are used to shift the bits of a number left or right, thereby multiplying or dividing the number by two, respectively. They can be used when we have to multiply or divide a number by two. 

Syntax: 

Types of Shift Operators:

Shift Operators are further divided into 3 types. These are:

  • Signed Right shift operator (>>)
  • Unsigned Right shift operator (>>>)
  • Left shift operator(<<)
Note: For more detail about the Shift Operators in Java, refer Shift Operator in Java .

program to implement all Bitwise operators in java for user input

Explanation.

  This program prompts the user to enter two numbers, num1 and num2. It then performs the following bitwise operations using the &, |, ^, ~, <<, >>, and >>> operators:

Bitwise AND Bitwise OR Bitwise XOR Bitwise NOT Bitwise Left Shift Bitwise Right Shift Bitwise Zero Fill Right Shift

Advantages 

The advantages of using Bitwise Operators in Java are:

  • Speed: Bitwise operations are much faster than arithmetic operations as they operate directly on binary representations of numbers.
  • Space Optimization: Bitwise operations can be used to store multiple values in a single variable, which can be useful when working with limited memory.
  • Bit Manipulation: Bitwise operators allow for precise control over individual bits of a number, which can be useful in various applications such as cryptography, error detection, and compression.
  • Code Simplification : Bitwise operations can simplify the code by reducing the number of conditional statements and loops required to perform certain tasks.

In summary, Bitwise Operators are an important tool for optimizing performance, improving code readability, and reducing code complexity in Java applications.

author

Please Login to comment...

Similar reads.

  • java-basics
  • Java-Operators
  • Best PS5 SSDs in 2024: Top Picks for Expanding Your Storage
  • Best Nintendo Switch Controllers in 2024
  • Xbox Game Pass Ultimate: Features, Benefits, and Pricing in 2024
  • Xbox Game Pass vs. Xbox Game Pass Ultimate: Which is Right for You?
  • Full Stack Developer Roadmap [2024 Updated]

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

What is the ^= operator? [closed]

I just came across an answer here on SO where a code example (in what I thought was java) used an operator I have never seen before: ^= . I searched google and SO and haven't been able to find it anywhere else and when I tried to test it out using java, eclipse went crazy. Maybe it was just a typo in the answer, I'm not sure. What is this operator? Does it have a name? What language is it from or used in?

  • bitwise-operators

takendarkk's user avatar

6 Answers 6

It is the C/C++/C#/Java/Javascript/Perl bitwise xor assignment operator.

ldav1s's user avatar

This is the C/C++/C#/Java/Javascript/Perl/PHP/Pike bitwise XOR assignment operator.

An XOR (exclusive or) conditional statement evaluates to true if and only if one of the two operands involved is true.

In the same way that you can use += -= *= /= etc... this operator can be combined with an equals sign to perform assignment upon completion.

See Java Operators .

It would depend on the language, but ^ is typically an exclusive-or (example languages: java, c-family); a ^= b is shorthand for a = a^b.

Scott Hunter's user avatar

  • @csmckelvey Look att en.wikipedia.org/wiki/Xor The truth-table: 0 ^ 0 = 0, 0 ^ 1 = 1, 1 ^ 0 = 1, 1 ^ 1 = 0 –  some Commented Dec 27, 2013 at 1:28

take a look here

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html and http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html

but it is a Bitwise Exclusive or with assignment

Doon's user avatar

In jQuery it means "starting with this"

For example id^='my_'

means "id starts with 'my_'"

dkellner's user avatar

  • 1 Why write an answer about jQuery if the question is about Java? (see tags) –  Aurelio De Rosa Commented Dec 27, 2013 at 1:43
  • @AurelioDeRosa At the time when this answer was written, there where no tag about java, only operators . –  some Commented Dec 27, 2013 at 2:44
  • 1 Yep, the text still ends like "What language is it from or used in?" –  dkellner Commented Dec 27, 2013 at 8:05

In the php manual it says that ^ is the bitwise XOR operator. Here's the link

Dries's user avatar

Not the answer you're looking for? Browse other questions tagged java operators bitwise-operators or ask your own question .

  • The Overflow Blog
  • The evolution of full stack engineers
  • One of the best ways to get value for AI coding tools: generating tests
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • Staging Ground Reviewer Motivation
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • NSolve uses all CPU resources
  • The action matters if intention its to just take good action and not action itself?
  • Can a V22 Osprey operate with only one propeller?
  • What is the origin of 找碴?
  • Can Cantrip Connection be used with innate cantrips?
  • How can I verify integrity of the document types?
  • Is a thing just a class with only one member?
  • How much could gravity increase before a military tank is crushed
  • How much technological progress could a group of modern people make in a century?
  • Does hydrogen peroxide work as a rocket fuel oxidizer by itself?
  • How to prove that the Greek cross tiles the plane?
  • Philosophical dogma hindering scientific progress?
  • What are the pros and cons of the classic portfolio by Wealthfront?
  • Why is the area covered by 1 steradian (in a sphere) circular in shape?
  • Father and Son treasure hunters that ends with finding one last shipwreck (childrens/young adult)
  • Is it possible for one wing to stall due to icing while the other wing doesn't ice?
  • How can I remove this towel rail mount from my wall?
  • Proving that a pair of "snow angels" cannot tile the plane
  • Can I repeat link labels several times on a web page without hurting SEO by using meta attributes?
  • Problem to find 32768 Hz crystal with 0.1 pF of Cshunt
  • Was Willy Wonka correct when he accused Charlie of stealing Fizzy Lifting Drinks?
  • Why are some Cloudflare challenges CPU intensive?
  • BASH - Find file with regex - Non-recursively delete number-only filenames in directory
  • Problem with the hinge mechanism of my folding bike (Smart Truck 300, made ~2016)

xor assignment operator

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Boolean logical operators - AND, OR, NOT, XOR

  • 5 contributors

The logical Boolean operators perform logical operations with bool operands. The operators include the unary logical negation ( ! ), binary logical AND ( & ), OR ( | ), and exclusive OR ( ^ ), and the binary conditional logical AND ( && ) and OR ( || ).

  • Unary ! (logical negation) operator.
  • Binary & (logical AND) , | (logical OR) , and ^ (logical exclusive OR) operators. Those operators always evaluate both operands.
  • Binary && (conditional logical AND) and || (conditional logical OR) operators. Those operators evaluate the right-hand operand only if it's necessary.

For operands of the integral numeric types , the & , | , and ^ operators perform bitwise logical operations. For more information, see Bitwise and shift operators .

  • Logical negation operator !

The unary prefix ! operator computes logical negation of its operand. That is, it produces true , if the operand evaluates to false , and false , if the operand evaluates to true :

The unary postfix ! operator is the null-forgiving operator .

  • Logical AND operator &

The & operator computes the logical AND of its operands. The result of x & y is true if both x and y evaluate to true . Otherwise, the result is false .

The & operator always evaluates both operands. When the left-hand operand evaluates to false , the operation result is false regardless of the value of the right-hand operand. However, even then, the right-hand operand is evaluated.

In the following example, the right-hand operand of the & operator is a method call, which is performed regardless of the value of the left-hand operand:

The conditional logical AND operator && also computes the logical AND of its operands, but doesn't evaluate the right-hand operand if the left-hand operand evaluates to false .

For operands of the integral numeric types , the & operator computes the bitwise logical AND of its operands. The unary & operator is the address-of operator .

  • Logical exclusive OR operator ^

The ^ operator computes the logical exclusive OR, also known as the logical XOR, of its operands. The result of x ^ y is true if x evaluates to true and y evaluates to false , or x evaluates to false and y evaluates to true . Otherwise, the result is false . That is, for the bool operands, the ^ operator computes the same result as the inequality operator != .

For operands of the integral numeric types , the ^ operator computes the bitwise logical exclusive OR of its operands.

  • Logical OR operator |

The | operator computes the logical OR of its operands. The result of x | y is true if either x or y evaluates to true . Otherwise, the result is false .

The | operator always evaluates both operands. When the left-hand operand evaluates to true , the operation result is true regardless of the value of the right-hand operand. However, even then, the right-hand operand is evaluated.

In the following example, the right-hand operand of the | operator is a method call, which is performed regardless of the value of the left-hand operand:

The conditional logical OR operator || also computes the logical OR of its operands, but doesn't evaluate the right-hand operand if the left-hand operand evaluates to true .

For operands of the integral numeric types , the | operator computes the bitwise logical OR of its operands.

  • Conditional logical AND operator &&

The conditional logical AND operator && , also known as the "short-circuiting" logical AND operator, computes the logical AND of its operands. The result of x && y is true if both x and y evaluate to true . Otherwise, the result is false . If x evaluates to false , y isn't evaluated.

In the following example, the right-hand operand of the && operator is a method call, which isn't performed if the left-hand operand evaluates to false :

The logical AND operator & also computes the logical AND of its operands, but always evaluates both operands.

  • Conditional logical OR operator ||

The conditional logical OR operator || , also known as the "short-circuiting" logical OR operator, computes the logical OR of its operands. The result of x || y is true if either x or y evaluates to true . Otherwise, the result is false . If x evaluates to true , y isn't evaluated.

In the following example, the right-hand operand of the || operator is a method call, which isn't performed if the left-hand operand evaluates to true :

The logical OR operator | also computes the logical OR of its operands, but always evaluates both operands.

Nullable Boolean logical operators

For bool? operands, the & (logical AND) and | (logical OR) operators support the three-valued logic as follows:

The & operator produces true only if both its operands evaluate to true . If either x or y evaluates to false , x & y produces false (even if another operand evaluates to null ). Otherwise, the result of x & y is null .

The | operator produces false only if both its operands evaluate to false . If either x or y evaluates to true , x | y produces true (even if another operand evaluates to null ). Otherwise, the result of x | y is null .

The following table presents that semantics:

x y x&y x|y
true true true true
true false false true
true null null true
false true false true
false false false false
false null false null
null true null true
null false false null
null null null null

The behavior of those operators differs from the typical operator behavior with nullable value types. Typically, an operator that is defined for operands of a value type can be also used with operands of the corresponding nullable value type. Such an operator produces null if any of its operands evaluates to null . However, the & and | operators can produce non-null even if one of the operands evaluates to null . For more information about the operator behavior with nullable value types, see the Lifted operators section of the Nullable value types article.

You can also use the ! and ^ operators with bool? operands, as the following example shows:

The conditional logical operators && and || don't support bool? operands.

  • Compound assignment

For a binary operator op , a compound assignment expression of the form

is equivalent to

except that x is only evaluated once.

The & , | , and ^ operators support compound assignment, as the following example shows:

The conditional logical operators && and || don't support compound assignment.

Operator precedence

The following list orders logical operators starting from the highest precedence to the lowest:

Use parentheses, () , to change the order of evaluation imposed by operator precedence:

For the complete list of C# operators ordered by precedence level, see the Operator precedence section of the C# operators article.

Operator overloadability

A user-defined type can overload the ! , & , | , and ^ operators. When a binary operator is overloaded, the corresponding compound assignment operator is also implicitly overloaded. A user-defined type can't explicitly overload a compound assignment operator.

A user-defined type can't overload the conditional logical operators && and || . However, if a user-defined type overloads the true and false operators and the & or | operator in a certain way, the && or || operation, respectively, can be evaluated for the operands of that type. For more information, see the User-defined conditional logical operators section of the C# language specification .

C# language specification

For more information, see the following sections of the C# language specification :

  • Logical negation operator
  • Logical operators
  • Conditional logical operators
  • C# operators and expressions
  • Bitwise and shift operators

Additional resources

IMAGES

  1. PPT

    xor assignment operator

  2. PPT

    xor assignment operator

  3. Bitwise Operators 3: The XOR Operation

    xor assignment operator

  4. Bitwise XOR operator in Python with Application

    xor assignment operator

  5. Python XOR: Operator User Guide

    xor assignment operator

  6. 10 Examples of XOR Operator In Java

    xor assignment operator

VIDEO

  1. Decision Theory

  2. CARAMELLDANSEN🤔

  3. Swap variables with XOR operator... #shorts #ytshortsindia #coding #javascript #programming

  4. Operators in C#

  5. 3 Operators in PHP

  6. QuickTip #127

COMMENTS

  1. Bitwise XOR assignment (^=)

    The bitwise XOR assignment (^=) operator performs bitwise XOR on the two operands and assigns the result to the left operand.

  2. Bitwise XOR (^)

    Bitwise XOR (^) The bitwise XOR (^) operator returns a number or BigInt whose binary representation has a 1 in each bit position for which the corresponding bits of either but not both operands are 1.

  3. How does the bitwise operator XOR ('^') work?

    The ^ operator performs an XOR on the bit values of each variable. XOR does the following: a = 1100. b = 1010. xor = 0110. x is the result of the XOR operation. If the bits are equal the result is 0 if they are different the result is 1. In your example the ^= performs XOR and assignment, and you swap the bits around between the two variables ...

  4. Bitwise XOR Operator in Programming

    Bitwise XOR Operator in Programming. 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.

  5. Bitwise and shift operators

    The bitwise and shift operators include unary bitwise complement, binary left and right shift, unsigned right shift, and the binary logical AND, OR, and exclusive OR operators. These operands take operands of the integral numeric types or the char type.

  6. Bitwise XOR Assignment (^=) Operator in JavaScript

    The Javascript Bitwise XOR assignment is represented by (^=). It is used to perform a bitwise XOR operation on both operands and assign the result to the left operand.

  7. C++ Bitwise XOR Assignment (^=) Operator

    In this C++ tutorial, you shall learn about Bitwise XOR Assignment operator, its syntax, and how to use this operator, with examples.

  8. Bitwise operations in C

    Bitwise operations in C In the C programming language, operations can be performed on a bit level using bitwise operators. Bitwise operations are contrasted by byte-level operations which characterize the bitwise operators' logical counterparts, the AND, OR, NOT operators.

  9. O.2

    Similar to the arithmetic assignment operators, C++ provides bitwise assignment operators in order to facilitate easy modification of variables. ... For example, instead of writing x = x >> 1;, you can write x >>= 1;.

  10. Java Bitwise XOR and assignment operator

    The Bitwise XOR and assignment operator (^=) assigns the first operand a value equal to the result of Bitwise XOR operation of two operands. (x ^= y) is equivalent to (x = x ^ y) The Bitwise XOR operator (^) is a binary operator which takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of ...

  11. JavaScript Bitwise

    Learn how to use JavaScript bitwise operators to manipulate binary numbers and perform bitwise logic.

  12. C Bitwise Operators: AND, OR, XOR, Complement and Shift Operations

    Learn how to use bitwise operators in C programming to manipulate bits and perform bitwise operations. Examples and explanations are provided.

  13. Expressions and operators

    Expressions and operators. This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more. At a high level, an expression is a valid unit of code that resolves to a value.

  14. Logical XOR operator in C++?

    How to use the XOR operator in C++ to perform logical operations on boolean values or bitwise operations on integers. Learn from the answers of other programmers on Stack Overflow.

  15. Assignment operators

    The bitwise XOR assignment operator uses the binary representation of both operands, does a bitwise XOR operation on them and assigns the result to the variable.

  16. Assignment Operators In C++

    In C++, the assignment operator forms the backbone of many algorithms and computational processes by performing a simple operation like assigning a value to a variable. It is denoted by equal sign ( = ) and provides one of the most basic operations in any programming language that is used to assign some value to the variables in C++ or in other ...

  17. C Bitwise XOR and assignment operator

    C - Bitwise XOR and assignment operator The Bitwise XOR and assignment operator (^=) assigns the first operand a value equal to the result of Bitwise XOR operation of two operands.

  18. Bitwise exclusive OR operator: ^

    The bitwise exclusive OR operator (^) compares each bit of its first operand to the corresponding bit of its second operand. If the bit in one of the operands is 0 and the bit in the other operand is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the operator must have integral ...

  19. Bitwise Operators in Java

    Learn how to use bitwise operators in Java with well written and explained articles, quizzes and practice questions on GeeksforGeeks.

  20. java

    This is the C/C++/C#/Java/Javascript/Perl/PHP/Pike bitwise XOR assignment operator. An XOR (exclusive or) conditional statement evaluates to true if and only if one of the two operands involved is true.

  21. Boolean logical operators

    The ^ operator computes the logical exclusive OR, also known as the logical XOR, of its operands. The result of x ^ y is true if x evaluates to true and y evaluates to false, or x evaluates to false and y evaluates to true.