DEV Community

DEV Community

Stephen Gbolagade

Posted on Jun 28, 2023

Bitwise Operations: A Simplified Guide for Beginners

Bitwise operator is one of the most important operators in programming languages. As easy as it is, it may be difficult for those who are learning it for the first time to understand the fun and what seems to be like magic behind it.

I will be explaining what exactly Bitwise is and give you a clear and simple explanation as if you're 10 years old .

Note: I will be using Python to run a few bitwise operations here. But the idea is not to write code but to explain the simple mathematics behind Bitwise operations.

Python needs no introduction, but I think explaining the concept of the programming language is important for absolute beginners.

Aside from printing "Hello world" , one of the basic fundamentals we learn for everything programming language is operators.

Just like the English language where you learn the Alphabet A - Z before you can construct words and then go on to become a writer, we also need to understand the basic stuff like operators and data types before jumping into real programming or engineering.

With no further Ado, let's explore the concept behind Bitwise Operators in programming languages.

What you need to know.

You must first of all understand ordinary binary operations, not deeply but the basic high school knowledge you have is okay.

Can you convert 25 (a natural or decimal number) to binary?

It's simple, the basic mathematics will give you 11001.

You should also be able to convert from binary back to decimal.

Bitwise entirely depends on Binary operations.

Recap : Binary operations are carried out in 1s and 0s… Of course, Binary is a number consisting of 1 and 0 only.

1 is otherwise used as ON while 0 is used as OFF, in some contexts, the same 1 and 0 can also be used as input and output.

But I'm going to use the concept of ON and OFF to explain Bitwise Operators.

The Bitwise Operators

Some Bitwise operators in programming languages:

  • AND (&)
  • Arithmetic Right SHIFT (>>)
  • Logical Right SHIFT (>>>)
  • Left SHIFT (<<)

Note that when performing a bitwise operation, it is common to represent the binary using a fixed shape of binary which is commonly a byte ( 8 bits make one byte ).

The 25 decimal we converted to binary earlier which gives us 11001 can be made to fit 8 bits shape simply by adding 0s at the back until it's 8-digits.

E.g., 11001 becomes 0001 1001 .

Although we can have derivatives like AND Assignment ("&=") which is just a combination of AND bitwise operator and assignment arithmetic operator.

Let's take them one after the other using a set of switches as an example. A set of switches is a binary number, remember we are dealing with bitwise.

For instance, if you're given 15 and you're asked to find it's bitwise, convert it to binary and the result is our switch.

Note : Switch in this context is simply what you know, like that kind of switch you use to ON and OFF your lamp.

1. Bitwise AND Operator ("&")

To perform AND bitwise operators, we need at least 2 switches to work with.

Let’s assume we are asked to find x in: let x = 6 & 15

6 is a decimal, likewise 15.

Step 1: Convert them to binary so that:

6 = 110 15 = 1111

Step 2: Make each of them the same shape

6 = 0000 0110 15 = 0000 1111

Now we can perform AND bitwise operator on the two switches since they're of the same shape.

The rule for AND bitwise operator is:

  • Keep the same element
  • Choose OFF over ON

Using that rule, we will have:

(6 & 15) = 0000 0110

You can safely remove all 0s that comes before the first 1, so that our final answer is

Since you're given the original number in decimal, you can convert binary 110 to decimal too.

So therefore (6 & 15) is 6.

That's the simple logic behind the operation. Remember, you always have to convert any given number to binary and ensure the two numbers are in the same shape.

You can calculate the same operation using python.

2. Bitwise OR Operator ("|")

Understanding AND operation has opened our understanding to other operations.

To perform OR operations,

The rule for OR is:

  • Keep the same
  • Choose ON over OFF

Using the same switches (6, 15). To find (6 | 15), we also do:

conversion and having equal shape

(6 | 15) = 0000 1111

Finally result for (6 | 15) is 1111, converting to decimal, we have 15.

The python program is:

3. Bitwise XOR Operator ("^")

XOR is otherwise known as eXclusive OR. And it follows the same pattern as the OR operation.

But the difference is you don't keep the same element , but you choose OFF if they are the same.

Here is what I mean using the rule:

  • For the same element, choose OFF
  • Choose ON over OFF.

To demonstrate that, let's do (6 ^ 15)

Ignore the same first 0s.

(6 ^ 15) = 1001

In decimal, (6 ^ 15) is 9.

4. Bitwise NOT Operator ("~")

The bitwise NOT Operator is quite different from the first 3 we've explained.

Bitwise NOT Operator doesn't compare , you don't have 2 sets of switches here but one.

The rule is simple:

  • If it's a binary, Flip the element, change ON to OFF, and vice versa. Meaning 0 becomes 1 and vice versa.
  • If it's a positive decimal, add 1 to it and make it negative
  • If it's a negative decimal, make it positive and subtract 1 from it

Let's use the same figures as an example.

(~ 6) becomes -7 (~ 15) becomes - 16. (~ -6) becomes 5 (~ -15) becomes 14

Here's the binary operation happening behind the scene using the rule.

6 = 0000 0110

If you flip, you'll have 1111 1001

So ~6 in bit level is 1111 1001

Now here is the confusion:

But decimal -7 is not the same as binary `1111 10001 `. Yeah, that's the surprising behavior of the NOT Operator.

For the negative or positive sign that's changing, the reason is simply because a number has its own sign, flipping the number also flips the sign.

For example, every natural number has a positive sign which is generally not written. Flipping the number will make the sign change.

That's why ~6 becomes -7 and ~-6 becomes 5

5. Bitwise Right SHIFT (">>")

Right shifting is just exactly as it is called, you simply move a number by the number of times you're given or need it to shift.

But before explaining, here is the rule .

  • Divide the given natural number by 2 and round it down.
  • If it's a binary, move each digital one by one to the right
  • When shifting, you'll lose a digital, replace it with 0

For example:

If you're to right 6 by 1, that is to move it forward by 1 or 6 >> 1

To get your answer in decimal, simply divide by 2 and your answer is 3.

6 >> 2 becomes 1.

explanation:

6 >> 2 is 6 ÷ (2×2) which is 6 ÷ 4

You'll get 1 remainder 2, throw the remainder out of the window.

8 >>> 3 is 8 ÷ (2×3) which is 8/6 = 1

Question : What if you want to right shift 6 in 3 times (6 >> 3)

Your quick understanding is 6 ÷ (2*2*2) which is 6÷9…. That's 0 remainders 3.

Round it down to 0.

If the number of times you're right shifting is bigger than the number you're shifting, the answer is 0.

For binary.

110 >> 1 becomes 011 or simply 11

converting 11 to decimal gives you 3.

110 >> 2 becomes 1.

So either binary way or decimal way, you'll get the same answer.

6. Bitwise Left SHIFT ("<<")

Of course, it is the opposite of the Right shift bitwise operation.

The rule for BITWISE Left shift is as follows:

  • Multiply the natural number by 2 and round down.
  • If it's a binary, move backward by the number of shift

(6 << 1) becomes 6 x 2 = 12.

(6 << 2) becomes 6 x (2*2) = 24.

(6 << 3) becomes 6 x (2*2*2) = 48.

For binary, move the digit backward:

(110 << 1) becomes 1100 (110 << 2) becomes 11000 (110 << 3) becomes 110000

If you convert each of this binary to decimal, you should get 12, 24 and 48 as we've gotten above.

7 Bitwise Logical Right SHIFT (>>>)

Logical Right SHIFT is just like ordinary or arithmetic Right shift but, in Logical right shift, you fill zero from the back.

(110 >>> 1) becomes 011 (110 >>> 2) becomes 001

So basically, Logical right shift is simply adding the Zero you're supposed to throw away ( as in ordinary right shift ) to the back of the number.

Guess…. (111000 >>> 2) becomes???

For positive numbers like 6, 8 etc, the answer and rule will still be the same as the normal right shift.

So therefore (6 >>> 1) is 6 ÷ 2 which is 3.

If you convert 011 to decimal, you'll get 3 as well.

Zero coming first in binary really can be ignored, but logical Right shift decided to keep, logical indeed.

In some programming languages , they only have the Arithmetic Right SHIFT (>>).

Conclusion: Bitwise operations are simple!

I mean, they're simple, right?

In real life, you will hardly calculate Bitwise operations manually because you can simply run a program to calculate a huge operation in a few seconds.

But the idea of this article is to explain what's happening behind the scenes.

Thanks for reading!

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

hugaidas profile image

Bug of the month: Cannot convert a BigInt value to a number

Victoria - Apr 2

wewake-dev profile image

Solving Coding Problems using the Inclusion-Exclusion Principle and its variations

Wewake - Apr 15

shreyvijayvargiya profile image

What is an Abstract Syntax Tree in Programming?

shrey vijayvargiya - Apr 6

somadevtoo profile image

Difference between WHERE vs HAVING Clause in SQL

Soma - Apr 21

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

  • Skip to main content
  • Select language
  • Skip to search
  • Expressions and operators
  • Operator precedence

Left-hand-side expressions

« Previous Next »

This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.

A complete and detailed list of operators and expressions is also available in the reference .

JavaScript has the following types of operators. This section describes the operators and contains information about operator precedence.

  • Assignment operators
  • Comparison operators
  • Arithmetic operators
  • Bitwise operators

Logical operators

String operators, conditional (ternary) operator.

  • Comma operator

Unary operators

  • Relational operator

JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:

For example, 3+4 or x*y .

A unary operator requires a single operand, either before or after the operator:

For example, x++ or ++x .

An assignment operator assigns a value to its left operand based on the value of its right operand. The simple 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 .

There are also compound assignment operators that are shorthand for the operations listed in the following table:

Destructuring

For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in comparing the operands numerically. The sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. These operators do not attempt to convert the operands to compatible types before checking equality. The following table describes the comparison operators in terms of this sample code:

Note:  ( => ) is not an operator, but the notation for Arrow functions .

An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value. The standard arithmetic operators are addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces Infinity ). For example:

In addition to the standard arithmetic operations (+, -, * /), JavaScript provides the arithmetic operators listed in the following table:

A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

The following table summarizes JavaScript's bitwise operators.

Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:

  • The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones). Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32 bit integer: Before: 11100110111110100000000000000110000000000001 After: 10100000000000000110000000000001
  • Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
  • The operator is applied to each pair of bits, and the result is constructed bitwise.

For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:

Note that all 32 bits are inverted using the Bitwise NOT operator, and that values with the most significant (left-most) bit set to 1 represent negative numbers (two's-complement representation).

Bitwise shift operators

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

Shift operators convert their operands to thirty-two-bit integers and return a result of the same type as the left operand.

The shift operators are listed in the following table.

Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. The logical operators are described in the following table.

Examples of expressions that can be converted to false are those that evaluate to null, 0, NaN, the empty string (""), or undefined.

The following code shows examples of the && (logical AND) operator.

The following code shows examples of the || (logical OR) operator.

The following code shows examples of the ! (logical NOT) operator.

Short-circuit evaluation

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

  • false && anything is short-circuit evaluated to false.
  • true || anything is short-circuit evaluated to true.

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.

For example,

The shorthand assignment operator += can also be used to concatenate strings.

The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:

If condition is true, the operator has the value of val1 . Otherwise it has the value of val2 . You can use the conditional operator anywhere you would use a standard operator.

This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the value "minor" to status .

The comma operator ( , ) simply evaluates both of its operands and returns the value of the last operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop.

For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to update two variables at once. The code prints the values of the diagonal elements in the array:

A unary operation is an operation with only one operand.

The delete operator deletes an object, an object's property, or an element at a specified index in an array. The syntax is:

where objectName is the name of an object, property is an existing property, and index is an integer representing the location of an element in an array.

The fourth form is legal only within a with statement, to delete a property from an object.

You can use the delete operator to delete variables declared implicitly but not those declared with the var statement.

If the delete operator succeeds, it sets the property or element to undefined . The delete operator returns true if the operation is possible; it returns false if the operation is not possible.

Deleting array elements

When you delete an array element, the array length is not affected. For example, if you delete a[3] , a[4] is still a[4] and a[3] is undefined.

When the delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete . However, trees[3] is still addressable and returns undefined .

If you want an array element to exist but have an undefined value, use the undefined keyword instead of the delete operator. In the following example, trees[3] is assigned the value undefined , but the array element still exists:

The typeof operator is used in either of the following ways:

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.

Suppose you define the following variables:

The typeof operator returns the following results for these variables:

For the keywords true and null , the typeof operator returns the following results:

For a number or string, the typeof operator returns the following results:

For property values, the typeof operator returns the type of value the property contains:

For methods and functions, the typeof operator returns results as follows:

For predefined objects, the typeof operator returns results as follows:

The void operator is used in either of the following ways:

The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.

You can use the void operator to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.

The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, void(0) evaluates to undefined , which has no effect in JavaScript.

The following code creates a hypertext link that submits a form when the user clicks it.

Relational operators

A relational operator compares its operands and returns a Boolean value based on whether the comparison is true.

The in operator returns true if the specified property is in the specified object. The syntax is:

where propNameOrNumber is a string or numeric expression representing a property name or array index, and objectName is the name of an object.

The following examples show some uses of the in operator.

The instanceof operator returns true if the specified object is of the specified object type. The syntax is:

where objectName is the name of the object to compare to objectType , and objectType is an object type, such as Date or Array .

Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.

For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.

The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.

The following table describes the precedence of operators, from highest to lowest.

A more detailed version of this table, complete with links to additional details about each operator, may be found in JavaScript Reference .

  • Expressions

An expression is any valid unit of code that resolves to a value.

Every syntactically valid expression resolves to some value but conceptually, there are two types of expressions: with side effects (for example: those that assign value to a variable) and those that in some sense evaluates and therefore resolves to value.

The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven to the variable x . The expression itself evaluates to seven.

The code 3 + 4 is an example of the second expression type. This expression uses the + operator to add three and four together without assigning the result, seven, to a variable. JavaScript has the following expression categories:

  • Arithmetic: evaluates to a number, for example 3.14159. (Generally uses arithmetic operators .)
  • String: evaluates to a character string, for example, "Fred" or "234". (Generally uses string operators .)
  • Logical: evaluates to true or false. (Often involves logical operators .)
  • Primary expressions: Basic keywords and general expressions in JavaScript.
  • Left-hand-side expressions: Left values are the destination of an assignment.

Primary expressions

Basic keywords and general expressions in JavaScript.

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this either with the dot or the bracket notation:

Suppose a function called validate validates an object's value property, given the object and the high and low values:

You could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example:

  • Grouping operator

The grouping operator ( ) controls the precedence of evaluation in expressions. For example, you can override multiplication and division first, then addition and subtraction to evaluate addition first.

Comprehensions

Comprehensions are an experimental JavaScript feature, targeted to be included in a future ECMAScript version. There are two versions of comprehensions:

Comprehensions exist in many programming languages and allow you to quickly assemble a new array based on an existing one, for example.

Left values are the destination of an assignment.

You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types. Use new as follows:

The super keyword is used to call functions on an object's parent. It is useful with classes to call the parent constructor, for example.

Spread operator

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

Example: Today if you have an array and want to create a new array with the existing one being part of it, the array literal syntax is no longer sufficient and you have to fall back to imperative code, using a combination of push , splice , concat , etc. With spread syntax this becomes much more succinct:

Similarly, the spread operator works with function calls:

Document Tags and Contributors

  • l10n:priority
  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • 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
  • Conditional (ternary) Operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • 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: can't access lexical declaration`X' before initialization
  • 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 delete non-configurable array element
  • 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
  • Skip to main content

UDN Web Docs: MDN Backup

  • 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.

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Using bitwise XOR assignment

Specifications, browser compatibility.

  • Assignment operators in the JS guide
  • Bitwise XOR operator
  • 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
  • Using promises
  • Iterators and generators
  • Meta programming
  • JavaScript modules
  • Client-side JavaScript frameworks
  • Client-side web APIs
  • 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:
  • AggregateError
  • ArrayBuffer
  • AsyncFunction
  • BigInt64Array
  • BigUint64Array
  • FinalizationRegistry
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • ReferenceError
  • SharedArrayBuffer
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Addition (+)
  • Addition assignment (+=)
  • Assignment (=)
  • Bitwise AND (&)
  • Bitwise AND assignment (&=)
  • Bitwise NOT (~)
  • Bitwise OR (|)
  • Bitwise OR assignment (|=)
  • Bitwise XOR (^)
  • Comma operator (,)
  • Conditional (ternary) operator
  • Decrement (--)
  • Destructuring assignment
  • Division (/)
  • Division assignment (/=)
  • Equality (==)
  • Exponentiation (**)
  • Exponentiation assignment (**=)
  • Function expression
  • Greater than (>)
  • Greater than or equal (>=)
  • Grouping operator ( )
  • Increment (++)
  • Inequality (!=)
  • Left shift (<<)
  • Left shift assignment (<<=)
  • Less than (<)
  • Less than or equal (<=)
  • Logical AND (&&)
  • Logical AND assignment (&&=)
  • Logical NOT (!)
  • Logical OR (||)
  • Logical OR assignment (||=)
  • Logical nullish assignment (??=)
  • Multiplication (*)
  • Multiplication assignment (*=)
  • Nullish coalescing operator (??)
  • Object initializer
  • Operator precedence
  • Optional chaining (?.)
  • Pipeline operator (|>)
  • Property accessors
  • Remainder (%)
  • Remainder assignment (%=)
  • Right shift (>>)
  • Right shift assignment (>>=)
  • Spread syntax (...)
  • Strict equality (===)
  • Strict inequality (!==)
  • Subtraction (-)
  • Subtraction assignment (-=)
  • Unary negation (-)
  • Unary plus (+)
  • Unsigned right shift (>>>)
  • Unsigned right shift assignment (>>>=)
  • async function expression
  • class expression
  • delete operator
  • function* expression
  • in operator
  • new operator
  • void operator
  • async function
  • for await...of
  • function declaration
  • import.meta
  • try...catch
  • Arrow function expressions
  • Default parameters
  • Method definitions
  • Rest parameters
  • The arguments object
  • Private class fields
  • Public class fields
  • constructor
  • 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: can't access lexical declaration "x" before initialization
  • 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: "x" is not iterable
  • TypeError: More arguments needed
  • TypeError: Reduce of empty array with no initial value
  • TypeError: X.prototype.y called on incompatible type
  • TypeError: can't access dead object
  • TypeError: can't access property "x" of "y"
  • TypeError: can't assign to property "x" on "y": not an object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't delete non-configurable array element
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cannot use "in" operator to search for "x" in "y"
  • TypeError: cyclic object value
  • TypeError: invalid "instanceof" 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

This browser is no longer supported.

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

Bitwise and shift operators (C# reference)

  • 9 contributors

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.

  • Unary ~ (bitwise complement) operator
  • Binary << (left shift) , >> (right shift) , and >>> (unsigned right shift) operators
  • Binary & (logical AND) , | (logical OR) , and ^ (logical exclusive OR) operators

Those operators are defined for the int , uint , long , and ulong types. When both operands are of other integral types ( sbyte , byte , short , ushort , or char ), their values are converted to the int type, which is also the result type of an operation. When operands are of different integral types, their values are converted to the closest containing integral type. For more information, see the Numeric promotions section of the C# language specification . The compound operators (such as >>= ) don't convert their arguments to int or have the result type as int .

The & , | , and ^ operators are also defined for operands of the bool type. For more information, see Boolean logical operators .

Bitwise and shift operations never cause overflow and produce the same results in checked and unchecked contexts.

  • Bitwise complement operator ~

The ~ operator produces a bitwise complement of its operand by reversing each bit:

You can also use the ~ symbol to declare finalizers. For more information, see Finalizers .

Left-shift operator <<

The << operator shifts its left-hand operand left by the number of bits defined by its right-hand operand. For information about how the right-hand operand defines the shift count, see the Shift count of the shift operators section.

The left-shift operation discards the high-order bits that are outside the range of the result type and sets the low-order empty bit positions to zero, as the following example shows:

Because the shift operators are defined only for the int , uint , long , and ulong types, the result of an operation always contains at least 32 bits. If the left-hand operand is of another integral type ( sbyte , byte , short , ushort , or char ), its value is converted to the int type, as the following example shows:

Right-shift operator >>

The >> operator shifts its left-hand operand right by the number of bits defined by its right-hand operand. For information about how the right-hand operand defines the shift count, see the Shift count of the shift operators section.

The right-shift operation discards the low-order bits, as the following example shows:

The high-order empty bit positions are set based on the type of the left-hand operand as follows:

If the left-hand operand is of type int or long , the right-shift operator performs an arithmetic shift: the value of the most significant bit (the sign bit) of the left-hand operand is propagated to the high-order empty bit positions. That is, the high-order empty bit positions are set to zero if the left-hand operand is non-negative and set to one if it's negative.

If the left-hand operand is of type uint or ulong , the right-shift operator performs a logical shift: the high-order empty bit positions are always set to zero.

Use the unsigned right-shift operator to perform a logical shift on operands of signed integer types. This is preferred to casting a left-hand operand to an unsigned type and then casting the result of a shift operation back to a signed type.

Unsigned right-shift operator >>>

Available in C# 11 and later, the >>> operator shifts its left-hand operand right by the number of bits defined by its right-hand operand. For information about how the right-hand operand defines the shift count, see the Shift count of the shift operators section.

The >>> operator always performs a logical shift. That is, the high-order empty bit positions are always set to zero, regardless of the type of the left-hand operand. The >> operator performs an arithmetic shift (that is, the value of the most significant bit is propagated to the high-order empty bit positions) if the left-hand operand is of a signed type. The following example demonstrates the difference between >> and >>> operators for a negative left-hand operand:

  • Logical AND operator &

The & operator computes the bitwise logical AND of its integral operands:

For bool operands, the & operator computes the logical AND of its operands. The unary & operator is the address-of operator .

  • Logical exclusive OR operator ^

The ^ operator computes the bitwise logical exclusive OR, also known as the bitwise logical XOR, of its integral operands:

For bool operands, the ^ operator computes the logical exclusive OR of its operands.

  • Logical OR operator |

The | operator computes the bitwise logical OR of its integral operands:

For bool operands, the | operator computes the logical OR of its 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 following example demonstrates the usage of compound assignment with bitwise and shift operators:

Because of numeric promotions , the result of the op operation might be not implicitly convertible to the type T of x . In such a case, if op is a predefined operator and the result of the operation is explicitly convertible to the type T of x , a compound assignment expression of the form x op= y is equivalent to x = (T)(x op y) , except that x is only evaluated once. The following example demonstrates that behavior:

Operator precedence

The following list orders bitwise and shift operators starting from the highest precedence to the lowest:

  • Shift operators << , >> , and >>>

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.

Shift count of the shift operators

For the built-in shift operators << , >> , and >>> , the type of the right-hand operand must be int or a type that has a predefined implicit numeric conversion to int .

For the x << count , x >> count , and x >>> count expressions, the actual shift count depends on the type of x as follows:

If the type of x is int or uint , the shift count is defined by the low-order five bits of the right-hand operand. That is, the shift count is computed from count & 0x1F (or count & 0b_1_1111 ).

If the type of x is long or ulong , the shift count is defined by the low-order six bits of the right-hand operand. That is, the shift count is computed from count & 0x3F (or count & 0b_11_1111 ).

The following example demonstrates that behavior:

As the preceding example shows, the result of a shift operation can be non-zero even if the value of the right-hand operand is greater than the number of bits in the left-hand operand.

Enumeration logical operators

The ~ , & , | , and ^ operators are also supported by any enumeration type. For operands of the same enumeration type, a logical operation is performed on the corresponding values of the underlying integral type. For example, for any x and y of an enumeration type T with an underlying type U , the x & y expression produces the same result as the (T)((U)x & (U)y) expression.

You typically use bitwise logical operators with an enumeration type that is defined with the Flags attribute. For more information, see the Enumeration types as bit flags section of the Enumeration types 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.

If a user-defined type T overloads the << , >> , or >>> operator, the type of the left-hand operand must be T . In C# 10 and earlier, the type of the right-hand operand must be int ; beginning with C# 11, the type of the right-hand operand of an overloaded shift operator can be any.

C# language specification

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

  • Bitwise complement operator
  • Shift operators
  • Logical operators
  • Numeric promotions
  • C# 11 - Relaxed shift requirements
  • C# 11 - Logical right-shift operator
  • C# operators and expressions
  • Boolean logical operators

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

This page is Ready to Use

bitwise xor assignment

Performs a bitwise exclusive OR on a variable and an expression and assigns the result to the variable.

See Remarks.

Using the ^= operator is exactly the same as specifying:

The ^= operator looks at the binary representation of the values of two expressions and does a bitwise exclusive OR operation on them. The result of this operation behaves as follows:

When one, and only one, of the expressions has a 1 in a digit, the result has a 1 in that digit. Otherwise, the result has a 0 in that digit.

Other articles

  • Bitwise XOR Operator (^)

Attributions

Microsoft Developer Network: Article

  • Accessibility
  • 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

  • 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.

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
  • 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
  • Java Basics
  • Java Tutorial
  • Java HelloWorld Program
  • Java Program Structure
  • Java Datatypes
  • Java Variable Types
  • Java Access Modifiers
  • Java Operators
  • Java Decision Making
  • Print array
  • Initialize array
  • Array of integers
  • Array of strings
  • Array of objects
  • Array of arrays
  • Iterate over array
  • Array For loop
  • Array while loop
  • Append element to array
  • Check if array is empty
  • Array average
  • Check if array contains
  • Array ForEach
  • Array - Find Index of Item
  • Concatenate arrays
  • Find smallest number in array
  • Find largest number in array
  • Array reverse
  • Classes and Objects
  • Inheritance
  • Polymorphism
  • Method Overloading
  • Method Overriding/
  • Abstraction
  • Abstract methods and classes
  • Encapsulation
  • Print string
  • Read string from console
  • Create string from Char array
  • Create string from Byte array
  • Concatenate two strings
  • Get index of the first Occurrence of substring
  • Get index of nth occurrence of substring
  • Check if two strings are equal
  • Check if string ends with specific suffix
  • Check if string starts with specific prefix
  • Check if string is blank
  • Check if string is empty
  • Check if string contains search substring
  • Validate if string is a Phone Number
  • Character Level
  • Get character at specific index in string
  • Get first character in string
  • Get last character from string
  • Transformations
  • Replace first occurrence of string
  • Replace all occurrences of a string
  • Join strings
  • Join strings in string array
  • Join strings in ArrayList
  • Reverse a string
  • Trim string
  • Split string
  • Remove whitespaces in string
  • Replace multiple spaces with single space
  • Comparisons
  • Compare strings lexicographically
  • Compare String and CharSequence
  • Compare String and StringBuffer
  • Java Exception Handling StringIndexOutOfBoundsException
  • Convert string to int
  • Convert string to float
  • Convert string to double
  • Convert string to long
  • Convert string to boolean
  • Convert int to string
  • Convert int to float
  • Convert int to double
  • Convert int to long
  • Convert int to char
  • Convert float to string
  • Convert float to int
  • Convert float to double
  • Convert float to long
  • Convert long to string
  • Convert long to float
  • Convert long to double
  • Convert long to int
  • Convert double to string
  • Convert double to float
  • Convert double to int
  • Convert double to long
  • Convert char to int
  • Convert boolean to string
  • Create a file
  • Read file as string
  • Write string to file
  • Delete File
  • Rename File
  • Download File from URL
  • Replace a String in File
  • Filter list of files or directories
  • Check if file is readable
  • Check if file is writable
  • Check if file is executable
  • Read contents of a file line by line using BufferedReader
  • Read contents of a File line by line using Stream
  • Check if n is positive or negative
  • Read integer from console
  • Add two integers
  • Count digits in number
  • Largest of three numbers
  • Smallest of three numbers
  • Even numbers
  • Odd numbers
  • Reverse a number
  • Prime Number
  • Print All Prime Numbers
  • Factors of a Number
  • Check Palindrome number
  • Check Palindrome string
  • Swap two numbers
  • Even or Odd number
  • Java Classes
  • ArrayList add()
  • ArrayList addAll()
  • ArrayList clear()
  • ArrayList clone()
  • ArrayList contains()
  • ArrayList ensureCapacity()
  • ArrayList forEach()
  • ArrayList get()
  • ArrayList indexOf()
  • ArrayList isEmpty()
  • ArrayList iterator()
  • ArrayList lastIndexOf()
  • ArrayList listIterator()
  • ArrayList remove()
  • ArrayList removeAll()
  • ArrayList removeIf()
  • ArrayList removeRange()
  • ArrayList retainAll()
  • ArrayList set()
  • ArrayList size()
  • ArrayList spliterator()
  • ArrayList subList()
  • ArrayList toArray()
  • ArrayList trimToSize()
  • HashMap clear()
  • HashMap clone()
  • HashMap compute()
  • HashMap computeIfAbsent()
  • HashMap computeIfPresent()
  • HashMap containsKey()
  • HashMap containsValue()
  • HashMap entrySet()
  • HashMap get()
  • HashMap isEmpty()
  • HashMap keySet()
  • HashMap merge()
  • HashMap put()
  • HashMap putAll()
  • HashMap remove()
  • HashMap size()
  • HashMap values()
  • HashSet add()
  • HashSet clear()
  • HashSet clone()
  • HashSet contains()
  • HashSet isEmpty()
  • HashSet iterator()
  • HashSet remove()
  • HashSet size()
  • HashSet spliterator()
  • Integer bitCount()
  • Integer byteValue()
  • Integer compare()
  • Integer compareTo()
  • Integer compareUnsigned()
  • Integer decode()
  • Integer divideUnsigned()
  • Integer doubleValue()
  • Integer equals()
  • Integer floatValue()
  • Integer getInteger()
  • Integer hashCode()
  • Integer highestOneBit()
  • Integer intValue()
  • Integer longValue()
  • Integer lowestOneBit()
  • Integer max()
  • Integer min()
  • Integer numberOfLeadingZeros()
  • Integer numberOfTrailingZeros()
  • Integer parseInt()
  • Integer parseUnsignedInt()
  • Integer remainderUnsigned()
  • Integer reverse()
  • Integer reverseBytes()
  • Integer rotateLeft()
  • Integer rotateRight()
  • Integer shortValue()
  • Integer signum()
  • Integer sum()
  • Integer toBinaryString()
  • Integer toHexString()
  • Integer toOctalString()
  • Integer toString()
  • Integer toUnsignedLong()
  • Integer toUnsignedString()
  • Integer valueOf()
  • StringBuilder append()
  • StringBuilder appendCodePoint()
  • StringBuilder capacity()
  • StringBuilder charAt()
  • StringBuilder chars()
  • StringBuilder codePointAt()
  • StringBuilder codePointBefore()
  • StringBuilder codePointCount()
  • StringBuilder codePoints()
  • StringBuilder delete()
  • StringBuilder deleteCharAt()
  • StringBuilder ensureCapacity()
  • StringBuilder getChars()
  • StringBuilder indexOf()
  • StringBuilder insert()
  • StringBuilder lastIndexOf()
  • StringBuilder length()
  • StringBuilder offsetByCodePoints()
  • StringBuilder replace()
  • StringBuilder reverse()
  • StringBuilder setCharAt()
  • StringBuilder setLength()
  • StringBuilder subSequence()
  • StringBuilder substring()
  • StringBuilder toString()
  • StringBuilder trimToSize()
  • Arrays.asList()
  • Arrays.binarySearch()
  • Arrays.copyOf()
  • Arrays.copyOfRange()
  • Arrays.deepEquals()
  • Arrays.deepToString()
  • Arrays.equals()
  • Arrays.fill()
  • Arrays.hashCode()
  • Arrays.sort()
  • Arrays.toString()
  • Random doubles()
  • Random ints()
  • Random longs()
  • Random next()
  • Random nextBoolean()
  • Random nextBytes()
  • Random nextDouble()
  • Random nextFloat()
  • Random nextGaussian()
  • Random nextInt()
  • Random nextLong()
  • Random setSeed()
  • Math random
  • Math signum
  • Math toDegrees
  • Math toRadians
  • Java Date & Time
  • ❯ Java Tutorial

Java Bitwise XOR Assignment (^=) Operator

Java bitwise xor assignment.

In Java, 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.

In this tutorial, we will learn how to use Bitwise XOR Assignment operator in Java, with examples.

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 Java Tutorial , we learned about Bitwise XOR Assignment Operator in Java, with examples.

Popular Courses by TutorialKart

App developement, web development, online tools.

Learn C practically and Get Certified .

Popular Tutorials

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

  • Getting Started with C
  • Your First C Program
  • C Variables, Constants and Literals
  • C Data Types
  • C Input Output (I/O)

C Programming Operators

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

Programming Arrays

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

Programming Pointers

  • Relationship Between Arrays and Pointers
  • C Pass Addresses and Pointers
  • C Dynamic Memory Allocation
  • C Array and Pointer Examples

Programming Strings

  • C Programming Strings
  • String Manipulations In C Programming Using Library Functions
  • String Examples in C Programming

Structure and Union

  • C structs and Pointers
  • C Structure and Function

Programmimg Files

  • C File Handling
  • C Files Examples

Additional Topics

  • C Keywords and Identifiers

C Precedence And Associativity Of Operators

  • C Bitwise Operators
  • C Preprocessor and Macros
  • C Standard Library Functions
  • 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.

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.

Related Tutorials

C Ternary Operator

  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial

Bitwise AND operator in Programming

  • Bitwise OR Operator (|) in Programming
  • Binary Operators in Programming
  • What are Operators in Programming?
  • Bitwise Operators in C++
  • Program for Bitwise Operators in C, C++, Java, Python, C# & JavaScript
  • C++ Bitwise Operator Overloading
  • Python Bitwise Operators
  • Bitwise Hacks for Competitive Programming
  • Bitwise Operators in C
  • AND(&) Bitwise Operator in JavaScript
  • Complete Reference for Bitwise Operators in Programming/Coding
  • PHP | Bitwise Operators
  • Bitwise Operators in Java
  • Bitwise OR Assignment (|=) Operator in JavaScript
  • Bitwise Logical Operations in R
  • bitset operator[] in C++ STL
  • Check if a Number is Odd or Even using Bitwise Operators
  • Bit Manipulation for Competitive Programming
  • JavaScript Bitwise Operators
  • Program to print ASCII Value of a character
  • Introduction of Programming Paradigms
  • Program for Hexadecimal to Decimal
  • Program for Decimal to Octal Conversion
  • A Freshers Guide To Programming
  • ASCII Vs UNICODE
  • How to learn Pattern printing easily?
  • Loop Unrolling
  • How to Learn Programming?
  • Program to Print the Trapezium Pattern

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 (&). 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 programming.

Table of Content

What is Bitwise AND?

  • Bitwise AND Operator
  • Bitwise AND Operator Syntax
  • Bitwise AND in C/C++
  • Bitwise AND in Java
  • Bitwise AND in Python
  • Bitwise AND in JavaScript
  • Bitwise AND in C#
  • Properties of Bitwise AND Operator
  • Applications of Bitwise AND Operator

The Bitwise AND operation ( & ) is a binary operation that operates on each bit of its operands independently. It returns a new value where each bit of the result is determined by applying the AND operation to the corresponding bits of the operands.

The truth table for the Bitwise AND operation is as follows:

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

The AND operation returns 1 (true) if the both the inputs are 1, and 0 (false) otherwise. This is why the output is 1 for the fourth row, where A and B have values = 1, and 0 for the first, second and third rows, where at least one of A or B has value = 0.

Bitwise AND Operator:

The Bitwise AND operator, represented by the symbol & , is used to perform a logical AND operation on corresponding bits of two integers. It compares each bit of the first operand with the corresponding bit of the second operand and yields a result where a bit is set only if both corresponding bits are set in the operands. Both the operands should be of integral types.

Bitwise AND Operator Syntax:

The Bitwise AND operator (&) is a fundamental component of bitwise operations in programming languages. It operates on individual bits of two integers, comparing each corresponding bit and producing a result based on whether both bits are set or not.

Below, we’ll explore the syntax of the Bitwise AND operator in various programming languages:

Bitwise AND in C/C++:

In C and C++, the syntax of the Bitwise AND operator is straightforward:

Here, operand1 and operand2 are the two integers on which the bitwise AND operation is performed. The result is stored in the variable result.

Bitwise AND in Java:

In Java, the Bitwise AND operator is represented by the symbol &:

Similar to C and C++, operand1 and operand2 are the two operands, and the result is stored in the variable result.

Bitwise AND in Python:

Python also supports bitwise operations, including the Bitwise AND operator, represented by the symbol &:

Similarly, operand1 and operand2 are the two operands, and the result is assigned to the variable result.

Bitwise AND in JavaScript:

In JavaScript, the Bitwise AND operator is also represented by the symbol &:

Again, operand1 and operand2 are the operands, and the result is stored in the variable result.

Bitwise AND in C#:

In C#, the Bitwise AND operator is similar to other languages, represented by the symbol &:

Once again, operand1 and operand2 are the operands, and the result is assigned to the variable result.

Properties of Bitwise AND Operator:

  • Commutativity: The order of operands does not affect the result of the bitwise AND operation. In other words, a & b yields the same result as b & a.
  • Identity : Performing a bitwise AND operation with zero (0) always results in zero. That is, a & 0 = 0 for any value of a.
  • Idempotence : Performing a bitwise AND operation with itself results in the same value. That is, a & a = a.

Applications of Bitwise AND Operator:

  • Masking : Bitwise AND is commonly used in masking operations to extract specific bits or flags from a bit pattern.
  • Checking Parity of a number : By performing a bitwise AND operation with 1, you can determine whether a number is even or odd. An even number & 1 results in 0, while an odd number & 1 results in 1.
  • Clearing Bits : To clear specific bits in an integer, you can use the bitwise AND operator with a mask where the bits you want to clear are set to 0.

Conclusion:

The Bitwise AND operator plays a crucial role in low-level programming, enabling efficient manipulation of individual bits within integers. Understanding its properties, syntax, and applications can significantly enhance your ability to write optimized and efficient code, especially in scenarios where performance is critical. By leveraging the bitwise AND operator effectively, programmers can unlock powerful capabilities for bitwise manipulation and optimization in their programs.

Please Login to comment...

Similar reads.

  • Programming

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Python Bitwise Operators

    bitwise xor assignment operator

  2. Python Bitwise Operators

    bitwise xor assignment operator

  3. Bitwise XOR Operator in C Language

    bitwise xor assignment operator

  4. C++ Bitwise XOR Operator

    bitwise xor assignment operator

  5. Swift 5.7: Advanced Operators (고급 연산자)

    bitwise xor assignment operator

  6. Bitwise Operators in C/C++

    bitwise xor assignment operator

VIDEO

  1. XOR Bitwise operator summary

  2. Bitwise XOR operator in C Language

  3. Chapter 2: Part 6.10 C++ Bitwise Operators (AND, OR, and XOR) አማርኛ

  4. Operators in C#

  5. Bitwise Operator in C(in Hindi)

  6. 3 Operators in PHP

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. Try it. Syntax. js. x ^= y Description. x ^= y is equivalent to x = x ^ y, except that the expression x is only evaluated once. Examples. Using bitwise XOR assignment. js.

  2. Bitwise XOR Operator in Programming

    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 ...

  3. 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. Syntax: Where -. Example: In this example, we will perform the basic Bitwise XOR assignment operation on both operands. Output: The number 2 is represented as 10 in binary, and ...

  4. 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. See the bitwise XOR operator for more details. Syntax Operator: x ^= y Meaning: x = x ^ y Example

  5. Bitwise Operations: A Simplified Guide for Beginners

    3. Bitwise XOR Operator ("^") XOR is otherwise known as eXclusive OR. And it follows the same pattern as the OR operation. But the difference is you don't keep the same element, but you choose OFF if they are the same.. Here is what I mean using the rule:

  6. Bitwise operators

    Bitwise operators. In This Article. Bitwise operators treat their operands as a sequence of 32 bits (zeroes and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return ...

  7. Expressions and operators

    Bitwise operators. A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript ...

  8. 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. The source for this interactive example is stored in a GitHub repository.

  9. 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 ...

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

    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. x ^= 2.

  11. Bitwise and shift operators

    Unsigned right-shift operator >>> Available in C# 11 and later, the >>> operator shifts its left-hand operand right by the number of bits defined by its right-hand operand. For information about how the right-hand operand defines the shift count, see the Shift count of the shift operators section.. The >>> operator always performs a logical shift. That is, the high-order empty bit positions ...

  12. bitwise xor assignment · WebPlatform Docs

    The ^= operator looks at the binary representation of the values of two expressions and does a bitwise exclusive OR operation on them. The result of this operation behaves as follows: When one, and only one, of the expressions has a 1 in a digit, the result has a 1 in that digit. Otherwise, the result has a 0 in that digit.

  13. Assignment Operators In C++

    The bitwise XOR assignment operator performs a bitwise XOR between the variable on the left and the value or variable on the right and assigns the result to the variable on the left. Syntax. variable ^ = value; This above expression is equivalent to the expression:

  14. 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 ...

  15. Java Bitwise XOR Assignment (^=) Operator

    In Java, 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. In this tutorial, we will learn how to use Bitwise XOR Assignment operator in Java, with examples. The syntax to compute bitwise XOR a value of 2 and value in variable x, and assign ...

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

    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. 12 = 00001100 (In Binary) 25 = 00011001 (In Binary)

  17. Bitwise Operators in C

    Bitwise Operators in C. In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.

  18. Bitwise Operators in Python

    Python bitwise operators are defined for the following built-in data types: int. bool. set and frozenset. dict (since Python 3.9) It's not a widely known fact, but bitwise operators can perform operations from set algebra, such as union, intersection, and symmetric difference, as well as merge and update dictionaries.

  19. Unclear about the use of Bitwise AND assignment

    The &= and the ++ together are the same as X = (X + 1) % 1024; but can be computed faster by the CPU. 1024-1 is 11 1111 1111 in binary, so for numbers where X < 1024, a bitwise AND will have no effect (since any bit & 1 = the same bit). Interesting things only start to happen where X ≥ 1024, so let's consider the iteration of the loop where X ...

  20. Bitwise AND operator in Programming

    The Bitwise AND operation (&) is a binary operation that operates on each bit of its operands independently. It returns a new value where each bit of the result is determined by applying the AND operation to the corresponding bits of the operands. The truth table for the Bitwise AND operation is as follows: A. B. A AND B.

  21. async function

    Description. An async function declaration creates an AsyncFunction object. Each time when an async function is called, it returns a new Promise which will be resolved with the value returned by the async function, or rejected with an exception uncaught within the async function. Async functions can contain zero or more await expressions.