- Skip to main content
- Skip to search
- Skip to select language
- Sign up for free
![](http://sektorel.online/777/templates/cheerup/res/banner1.gif)
Right shift assignment (>>=)
The right shift assignment ( >>= ) operator performs right shift on the two operands and assigns the result to the left operand.
Description
x >>= y is equivalent to x = x >> y , except that the expression x is only evaluated once.
Using right shift assignment
Specifications.
Specification |
---|
Browser compatibility
desktop | mobile | server | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
) | 1Toggle history | 12Toggle history | 1Toggle history | 3Toggle history | 1Toggle history | 18Toggle history | 4Toggle history | 10.1Toggle history | 1Toggle history | 1.0Toggle history | 4.4Toggle history | 1.0Toggle history | 0.10.0Toggle history |
- Assignment operators in the JS guide
- Right shift ( >> )
Loading search index…
No recent searches
No results for " Query here "
- to navigate
Search by FlexSearch
Example Reference
Right shift assignment (>>=).
The >>= operator performs right shift on the two operands and assigns the result to the left operand.
Description
x >>= y is equivalent to x = x >> y , except that the expression x is only evaluated once.
Using right shift assignment
Specifications.
Specification |
---|
Browser compatibility
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | Deno | Node.js | ||
1 | 12 | 1 | 3 | 1 | 18 | 4 | 10.1 | 1 | 1.0 | 4.4 | 1.0 | 0.10.0 |
- Assignment operators in the JS guide
- Right shift ( >> )
© 2005–2023 MDN contributors. Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift_assignment
- Skip to main content
![right shift assignment in javascript UDN Web Docs: MDN Backup](https://udn.realityripple.com/static/img/web-docs-black.png)
- Right shift assignment (>>=)
The right shift assignment operator ( >>= ) moves the specified amount of bits to the right 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 right shift assignment
Specifications.
Specification |
---|
Browser compatibility
Desktop | Mobile | Server | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | Android webview | Chrome for Android | Firefox for Android | Opera for Android | Safari on iOS | Samsung Internet | Node.js | |
Right shift assignment ( ) | Chrome 1 | Edge 12 | Firefox 1 | IE 3 | Opera 3 | Safari 1 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 1 | Samsung Internet Android 1.0 | nodejs 0.1.100 |
- Assignment operators in the JS guide
- Right shift 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 (^)
- Bitwise XOR assignment (^=)
- 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 (>>)
- 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
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 assignment, javascript assignment operators.
Assignment operators assign values to JavaScript variables.
Operator | Example | Same As |
---|---|---|
= | x = y | x = y |
+= | x += y | x = x + y |
-= | x -= y | x = x - y |
*= | x *= y | x = x * y |
/= | x /= y | x = x / y |
%= | x %= y | x = x % y |
**= | x **= y | x = x ** y |
Shift Assignment Operators
Operator | Example | Same As |
---|---|---|
<<= | x <<= y | x = x << y |
>>= | x >>= y | x = x >> y |
>>>= | x >>>= y | x = x >>> y |
Bitwise Assignment Operators
Operator | Example | Same As |
---|---|---|
&= | x &= y | x = x & y |
^= | x ^= y | x = x ^ y |
|= | x |= y | x = x | y |
Logical Assignment Operators
Operator | Example | Same As |
---|---|---|
&&= | x &&= y | x = x && (x = y) |
||= | x ||= y | x = x || (x = y) |
??= | x ??= y | x = x ?? (x = y) |
The = Operator
The Simple Assignment Operator assigns a value to a variable.
Simple Assignment Examples
The += operator.
The Addition Assignment Operator adds a value to a variable.
Addition Assignment Examples
The -= operator.
The Subtraction Assignment Operator subtracts a value from a variable.
Subtraction Assignment Example
The *= operator.
The Multiplication Assignment Operator multiplies a variable.
Multiplication Assignment Example
The **= operator.
The Exponentiation Assignment Operator raises a variable to the power of the operand.
Exponentiation Assignment Example
The /= operator.
The Division Assignment Operator divides a variable.
Division Assignment Example
The %= operator.
The Remainder Assignment Operator assigns a remainder to a variable.
Remainder Assignment Example
Advertisement
The <<= Operator
The Left Shift Assignment Operator left shifts a variable.
Left Shift Assignment Example
The >>= operator.
The Right Shift Assignment Operator right shifts a variable (signed).
Right Shift Assignment Example
The >>>= operator.
The Unsigned Right Shift Assignment Operator right shifts a variable (unsigned).
Unsigned Right Shift Assignment Example
The &= operator.
The Bitwise AND Assignment Operator does a bitwise AND operation on two operands and assigns the result to the the variable.
Bitwise AND Assignment Example
The |= operator.
The Bitwise OR Assignment Operator does a bitwise OR operation on two operands and assigns the result to the variable.
Bitwise OR Assignment Example
The ^= operator.
The Bitwise XOR Assignment Operator does a bitwise XOR operation on two operands and assigns the result to the variable.
Bitwise XOR Assignment Example
The &&= operator.
The Logical AND assignment operator is used between two values.
If the first value is true, the second value is assigned.
Logical AND Assignment Example
The &&= operator is an ES2020 feature .
The ||= Operator
The Logical OR assignment operator is used between two values.
If the first value is false, the second value is assigned.
Logical OR Assignment Example
The ||= operator is an ES2020 feature .
The ??= Operator
The Nullish coalescing assignment operator is used between two values.
If the first value is undefined or null, the second value is assigned.
Nullish Coalescing Assignment Example
The ??= operator is an ES2020 feature .
Test Yourself With Exercises
Use the correct assignment operator that will result in x being 15 (same as x = x + y ).
Start the Exercise
![right shift assignment in javascript Get Certified](https://www.w3schools.com/images/img_fullaccess_up_sep1_green_300.png)
COLOR PICKER
![right shift assignment in javascript colorpicker](https://www.w3schools.com/images/colorpicker2000.png)
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.
This page is Ready to Use
right shift assignment
Right shifts the value of a variable by the number of bits specified in the value of an expression, maintaining the sign, and assigns the result to the variable.
Using the >>= operator is exactly the same as specifying:
The >>= operator shifts the bits of result right by the number of bits specified in expression. The sign bit of result is used to fill the digits from the left. Digits shifted off the right are discarded. For example, after the following code is evaluated, temp has a value of -4: 14 (11110010 in binary) shifted right two bits equals -4 (11111100 in binary).
Other articles
- Bitwise Left Shift Operator (<<)
- Bitwise Right Shift Operator (>>)
- Unsigned Right Shift Operator (>>>)
Attributions
Microsoft Developer Network: Article
- Accessibility
- JavaScript - Home
- JavaScript - Introduction
- JavaScript - Comments
- JavaScript - Operators
- JavaScript - If Else
- JavaScript - Switch
- JavaScript - While Loop
- JavaScript - For Loop
- JavaScript - For In Loop
- JavaScript - For Of Loop
- JavaScript - Continue Statement
- JavaScript - Break Statement
- JavaScript - Label Statement
- JavaScript - Functions
- JavaScript - Math
- JavaScript - Array
- JavaScript - Q&A
![right shift assignment in javascript AlphaCodingSkills](https://www.alphacodingskills.com/imgfiles/ACS_Logo.png)
![right shift assignment in javascript Facebook Page](https://www.alphacodingskills.com/imgfiles/facebook.jpg)
- 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
JavaScript - right shift assignment operator
The Bitwise right shift assignment operator (>>=) assigns the first operand a value equal to the result of Bitwise right shift operation of two operands.
(x >>= y) is equivalent to (x = x >> y)
The Bitwise right shift operator (>>) takes the two numbers and right shift the bits of first operand by number of place specified by second operand. For example: for right shifting the bits of x by y places, the expression ( x>>y ) can be used. It is equivalent to dividing x by 2 y .
The example below describes how right shift operator works:
The code of using right shift operator (>>) is given below:
The output (value of txt ) after running above script will be:
Example: Find largest power of 2 less than or equal to given number
Consider an integer 1000. In the bit-wise format, it can be written as 1111101000. However, all bits are not written here. A complete representation will be 32 bit representation as given below:
Performing N = N | (N>>i) operation, where i = 1, 2, 4, 8, 16 will change all right side bit to 1. When applied on 1000, the result in 32 bit representation is given below:
Adding one to this result and then right shifting the result by one place will give largest power of 2 less than or equal to 1000.
The below code will calculate the largest power of 2 less than or equal to given number.
![AlphaCodingSkills Android App AlphaCodingSkills Android App](https://www.alphacodingskills.com/imgfiles/google-play.png)
- 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
- Java.lang Package
- 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
![right shift assignment in javascript TutorialsTonight Logo](https://www.tutorialstonight.com/assets/page-logo.png)
JAVASCRIPT ASSIGNMENT OPERATORS
In this tutorial, you will learn about all the different assignment operators in javascript and how to use them in javascript.
Assignment Operators
In javascript, there are 16 different assignment operators that are used to assign value to the variable. It is shorthand of other operators which is recommended to use.
The assignment operators are used to assign value based on the right operand to its left operand.
The left operand must be a variable while the right operand may be a variable, number, boolean, string, expression, object, or combination of any other.
One of the most basic assignment operators is equal = , which is used to directly assign a value.
![right shift assignment in javascript javascript assignment operator](https://www.tutorialstonight.com/assets/js/javascript-assignment-operator.webp)
Assignment Operators List
Here is the list of all assignment operators in JavaScript:
In the following table if variable a is not defined then assume it to be 10.
Operator | Description | Example | Equivalent to |
---|---|---|---|
= | a = 10 | a = 10 | |
+= | a += 10 | a = a + 10 | |
-= | a -= 10 | a = a - 10 | |
*= | a *= 10 | a = a * 10 | |
/= | a /= 10 | a = a / 10 | |
%= | a %= 10 | a = a % 10 | |
**= | a **= 2 | a = a ** 2 | |
<<= | a <<= 1 | a = a << 1 | |
>>= | a >>= 2 | a = a >> 2 | |
>>>= | a >>>= 1 | a = a >>> 1 | |
&= | a &= 4 | a = a & 4 | |
|= | a |= 2 | a = a | 2 | |
^= | a ^= 5 | a = a ^ 5 | |
&&= | a &&= 3 | a = a && 3 | |
||= | a ||= 4 | a = a || 4 | |
??= | a ??= 2 | a = a ?? 2 |
Assignment operator
The assignment operator = is the simplest value assigning operator which assigns a given value to a variable.
The assignment operators support chaining, which means you can assign a single value in multiple variables in a single line.
Addition assignment operator
The addition assignment operator += is used to add the value of the right operand to the value of the left operand and assigns the result to the left operand.
On the basis of the data type of variable, the addition assignment operator may add or concatenate the variables.
Subtraction assignment operator
The subtraction assignment operator -= subtracts the value of the right operand from the value of the left operand and assigns the result to the left operand.
If the value can not be subtracted then it results in a NaN .
Multiplication assignment operator
The multiplication assignment operator *= assigns the result to the left operand after multiplying values of the left and right operand.
Division assignment operator
The division assignment operator /= divides the value of the left operand by the value of the right operand and assigns the result to the left operand.
![](http://sektorel.online/777/templates/cheerup/res/banner1.gif)
Remainder assignment operator
The remainder assignment operator %= assigns the remainder to the left operand after dividing the value of the left operand by the value of the right operand.
Exponentiation assignment operator
The exponential assignment operator **= assigns the result of exponentiation to the left operand after exponentiating the value of the left operand by the value of the right operand.
Left shift assignment
The left shift assignment operator <<= assigns the result of the left shift to the left operand after shifting the value of the left operand by the value of the right operand.
Right shift assignment
The right shift assignment operator >>= assigns the result of the right shift to the left operand after shifting the value of the left operand by the value of the right operand.
Unsigned right shift assignment
The unsigned right shift assignment operator >>>= assigns the result of the unsigned right shift to the left operand after shifting the value of the left operand by the value of the right operand.
Bitwise AND assignment
The bitwise AND assignment operator &= assigns the result of bitwise AND to the left operand after ANDing the value of the left operand by the value of the right operand.
Bitwise OR assignment
The bitwise OR assignment operator |= assigns the result of bitwise OR to the left operand after ORing the value of left operand by the value of the right operand.
Bitwise XOR assignment
The bitwise XOR assignment operator ^= assigns the result of bitwise XOR to the left operand after XORing the value of the left operand by the value of the right operand.
Logical AND assignment
The logical AND assignment operator &&= assigns value to left operand only when it is truthy .
Note : A truthy value is a value that is considered true when encountered in a boolean context.
Logical OR assignment
The logical OR assignment operator ||= assigns value to left operand only when it is falsy .
Note : A falsy value is a value that is considered false when encountered in a boolean context.
Logical nullish assignment
The logical nullish assignment operator ??= assigns value to left operand only when it is nullish ( null or undefined ).
Unsigned right shift (>>>)
The >>> operator returns a number whose binary representation is the first operand shifted by the specified number of bits to the right. Excess bits shifted off to the right are discarded, and zero bits are shifted in from the left. This operation is also called "zero-filling right shift", because the sign bit becomes 0 , so the resulting number is always positive. Unsigned right shift does not accept BigInt values.
Description
Unlike other arithmetic and bitwise operators, the unsigned right shift operator does not accept BigInt values. This is because it fills the leftmost bits with zeroes, but conceptually, BigInts have an infinite number of leading sign bits, so there's no "leftmost bit" to fill with zeroes.
The operator operates on the left operand's bit representation in two's complement . Consider the 32-bit binary representations of the decimal (base 10) numbers 9 and -9 :
The binary representation under two's complement of the negative decimal (base 10) number -9 is formed by inverting all the bits of its opposite number, which is 9 and 00000000000000000000000000001001 in binary, and adding 1 .
In both cases, the sign of the binary number is given by its leftmost bit: for the positive decimal number 9 , the leftmost bit of the binary representation is 0 , and for the negative decimal number -9 , the leftmost bit of the binary representation is 1 .
Given those binary representations of the decimal (base 10) numbers 9 , and -9 :
For the positive number 9 , zero-fill right shift and sign-propagating right shift yield the same result: 9 >>> 2 yields 2 , the same as 9 >> 2 :
Notice how two rightmost bits, 01 , have been shifted off, and two zeroes have been shifted in from the left.
However, notice what happens for -9 : -9 >> 2 ( sign-propagating right shift ) yields -3 , but -9 >>> 2 (zero-fill right shift) yields 1073741821:
Notice how two rightmost bits, 11 , have been shifted off. For -9 >> 2 ( sign-propagating right shift ), two copies of the leftmost 1 bit have been shifted in from the left, which preserves the negative sign. On the other hand, for -9 >>> 2 (zero-fill right shift), zeroes have instead been shifted in from the left, so the negative sign of the number is not preserved, and the result is instead a (large) positive number.
If the left operand is a number with more than 32 bits, it will get the most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer:
The right operand will be converted to an unsigned 32-bit integer and then taken modulo 32, so the actual shift offset will always be a positive integer between 0 and 31, inclusive. For example, 100 >>> 32 is the same as 100 >>> 0 (and produces 100 ) because 32 modulo 32 is 0.
Using unsigned right shift
Unsigned right shift doesn't work with BigInts.
Specifications
Specification |
---|
Browser compatibility
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | Deno | Node.js | ||
1 | 12 | 1 | 3 | 1 | 18 | 4 | 10.1 | 1 | 1.0 | 4.4 | 1.0 | 0.10.0 |
- Bitwise operators in the JS guide
- Unsigned right shift assignment ( >>>= )
© 2005–2023 MDN contributors. Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift
- Trending Now
- Foundational Courses
- Data Science
- Practice Problem
- Machine Learning
- System Design
- DevOps Tutorial
Right Shift Operator (>>) in Programming
Right shift operator (>>), commonly found in programming languages, including C, C++, Java, and others, is used to shift the bits of a number to the right by a specified number of positions. Each shift moves all bits in the operand to the right by the number of positions indicated by the right operand.
![right shift assignment in javascript right shift assignment in javascript](https://media.geeksforgeeks.org/wp-content/uploads/20221219184254/Logical-Right-Shift.png)
Table of Content
- Right Shift Operator (>>) Definition
- Right Shift Operator (>>) Syntax
- Right Shift Operator (>>) Examples
- Right Shift Operator (>>) with Signed Integers
- Right Shift Operator (>>) with Unsigned Integers
- Right Shift Operator (>>) with Signed vs. Unsigned Integers
- Logical Right Shift
- Arithmetic Right Shift
- Logical Right Shift vs. Arithmetic Right Shift
- Right Shift Operator (>>) Optimization Techniques
- Bit Manipulation Hacks with Right Shift Operator
This comprehensive guide aims to provide a deep understanding of bitwise right shift operators, from the foundational principles to advanced optimization strategies.
Right Shift Operator (>>) Definition:
When you right-shift a binary number by n positions, each bit in the number is moved n positions to the right. This effectively divides the number by 2^n (equivalent to integer division by 2^n ). The rightmost n bits are discarded, and 0 bits are shifted in from the left.
Right Shift Operator (>>) Syntax:
The syntax of the bitwise right shift operator is simple and consistent across programming languages:
- operand : The value whose bits are to be shifted.
- n : The number of positions to shift the bits by.
Right Shift Operator (>>) Examples:
Consider the binary number 1101 0010 , which is 210 in decimal. If we right-shift it by 2 positions:
The result would be 0011 0100 , which is 52 in decimal. This is because each bit is shifted two positions to the right, and the vacant positions on the left are filled with 0 s.
Right Shift Operator (>>) with Signed Integers:
When using the bitwise right shift ( >> ) operator with signed integers, it’s essential to understand how the sign bit is preserved and the implications of this preservation. Let’s explore this with examples:
Preserving Sign Bit:
In signed integers, the leftmost bit (most significant bit) represents the sign of the number. When right-shifting signed integers, the sign bit is preserved, meaning it is replicated to fill the vacant leftmost positions.
In this example, when -8 is right-shifted by 1 position, the sign bit ( 1 ) is replicated, resulting in 1111 1100 , which represents -4 in decimal.
Use Case: Division by Powers of 2 with Signed Integers
In this case, -16 is right-shifted by 2 positions, which is equivalent to dividing -16 by 2**2 . The sign bit is preserved during the right shift, resulting in -4 .
Right Shift Operator (>>) with Unsigned Integers:
When using the bitwise right shift ( >> ) operator with unsigned integers, the behavior is simpler compared to signed integers. Let’s explore how the right shift operator works with unsigned integers:
Behavior with Unsigned Integers:
In unsigned integers, there is no sign bit, so the right shift operation simply shifts the bits to the right, filling the vacant leftmost positions with zeros.
In this example, when the unsigned integer 8 is right-shifted by 1 position, the bits are shifted to the right, and the vacant leftmost position is filled with 0 , resulting in 0000 0100 , which represents 4 in decimal.
Use Case: Division by Powers of 2 with Unsigned Integers
In this case, 16 is an unsigned integer, and right-shifting it by 2 positions is equivalent to dividing 16 by 2**2 . The bits are simply shifted to the right, filling the vacant leftmost positions with zeros, resulting in 0000 0100 , which represents 4 in decimal.
Right Shift Operator (>>) with Signed vs. Unsigned Integers:
Aspect | Signed Integers | Unsigned Integers |
---|---|---|
Sign Bit Preservation | Sign bit is preserved, replicated to fill vacant leftmost positions. | No sign bit, all bits are shifted to the right, filling vacant positions with zeros. |
Example | results in (Binary: ) | results in (Binary: ) |
Division by Powers of 2 | Right shift performs signed division by . | Right shift performs unsigned division by . |
Implementation in Programming | Behavior depends on language and compiler. Most use arithmetic right shift. | Always performs logical right shift. |
Logical Right Shift:
Bitwise logical right shift refers to the operation of shifting the bits of a binary number to the right by a specified number of positions while filling the vacant leftmost positions with zeros. This operation is commonly used with unsigned integers and is denoted by the >> operator in most programming languages.
Where operand is the value whose bits are to be shifted, and n is the number of positions to shift by.
- Unsigned Integer Division by Powers of 2 : Logical right shift can be used to divide unsigned integers by powers of 2 efficiently.
- Clearing Bits : Logical right shift is useful for clearing specific bits in a binary number, as shifting bits to the right fills the vacant leftmost positions with zeros.
Arithmetic Right Shift:
Bitwise arithmetic right shift is an operation used to shift the bits of a binary number to the right by a specified number of positions while preserving the sign of the number. This operation is commonly used with signed integers and is denoted by the >> operator in many programming languages.
- Signed Integer Division by Powers of 2 : Arithmetic right shift can be used to divide signed integers by powers of 2 efficiently while preserving the sign of the number.
- Preserving Sign Bit : Unlike logical right shift, arithmetic right shift preserves the sign bit, ensuring that the sign of the number remains unchanged.
Logical Right Shift vs. Arithmetic Right Shift:
- Logical right shift : In logical right shift, vacant leftmost positions are filled with zeros. It’s commonly used for unsigned integers.
- Arithmetic right shift : In arithmetic right shift, vacant leftmost positions are filled with the sign bit. It’s used for signed integers to preserve the sign of the number.
Let’s summarize the differences between bitwise logical right shift ( >> ) and bitwise arithmetic right shift ( >> ) in a table:
Aspect | Logical Right Shift (unsigned integers) | Arithmetic Right Shift (signed integers) |
---|---|---|
Sign Preservation | Does not preserve sign; fills vacant leftmost positions with zeros. | Preserves sign; replicates sign bit to fill vacant leftmost positions. |
Example | results in (Binary: ) | results in (Binary: ) |
Division by Powers of 2 | Performs unsigned division by . | Performs signed division by . |
Implementation in Programming | Performs logical right shift, filling vacant positions with zeros. | Performs arithmetic right shift, preserving the sign bit. |
Right Shift Operator (>>) Optimization Techniques:
1. division by powers of 2 :.
Right shifting a number by n positions is equivalent to dividing it by 2^n . This property is extensively used for optimization in situations where division by powers of 2 is required.
Example: In low-level programming or embedded systems, when dealing with hardware registers or memory addresses that are aligned to powers of 2, right shifting can be used to divide them effectively.
2. Faster Arithmetic Operations :
Right shifts are often utilized to optimize arithmetic operations, particularly in performance-critical applications.
Example: In algorithms where performance is critical, such as numerical computations or graphics rendering, replacing division by powers of 2 with right shifts can lead to significant performance gains.
3. Data Compression :
Bitwise operations, including right shifts, play a crucial role in data compression algorithms.
Example: In Huffman coding, right shifting can be used to encode symbols efficiently, especially when dealing with probabilities that are powers of 2.
4. Bit Manipulation :
Right shifts are fundamental for various bit manipulation tasks, such as extracting specific bits, checking bit flags, or packing/unpacking data structures.
Example: In networking protocols, when parsing headers, right shifting can be used to extract fields representing packet lengths, checksums, or protocol version numbers.
5. Masking and Filtering :
Right shifting can be combined with bitwise AND ( & ) to create masks for filtering out specific bits or extracting certain bit patterns.
Example: In image processing, right shifting can be used to reduce the color depth of an image by discarding the least significant bits, effectively creating a lower-resolution version of the image.
6. Encryption and Hashing :
Right shifts are employed in various cryptographic algorithms for bitwise mixing and diffusion of data.
Example: In block ciphers like AES (Advanced Encryption Standard), right shifts are part of the key expansion and encryption/decryption operations.
7. Fixed-Point Arithmetic :
Right shifts are used in fixed-point arithmetic to perform fractional division by powers of 2.
Example: In digital signal processing (DSP) applications, when working with fixed-point numbers, right shifts can be used to scale the result of mathematical operations.
Bit Manipulation Hacks with Right Shift Operator:
Bitwise right shift ( >> ) is a fundamental operation in bit manipulation and bit twiddling hacks. It is often used in combination with other bitwise operators to achieve various tasks efficiently. Here are some common bit manipulation and bit twiddling hacks that involve bitwise right shift:
1. Setting or Clearing Bits:
In set_bit , the bitwise OR operation ( | ) with (1 << n) sets the nth bit of the number to 1. In clear_bit , the bitwise AND operation ( & ) with the complement of (1 << n) clears the nth bit of the number.
2. Checking if a Number is a Power of 2:
A number is a power of 2 if it has only one bit set. The expression (num & (num - 1)) clears the lowest set bit, so if the result is zero and the number is not zero, then it is a power of 2.
3. Counting Set Bits (Population Count):
The loop iterates through each bit of the number and counts the bits that are set to 1 using the bitwise AND operation ( & ) with 1 .
4. Extracting the Lowest Set Bit:
The expression num & -num isolates the lowest set bit of the number by preserving only that bit and setting all other bits to 0.
5. Rotating Bits:
The expression (num >> n) | (num << (sizeof(num) * 8 - n)) rotates the bits of the number to the right by n positions.
6. Reversing Bits:
The loop iterates through each bit of the number, shifting and adding the bits to the reversed number to reverse them.
Please Login to comment...
Similar reads.
- Programming
- California Lawmakers Pass Bill to Limit AI Replicas
- Best 10 IPTV Service Providers in Germany
- Python 3.13 Releases | Enhanced REPL for Developers
- IPTV Anbieter in Deutschland - Top IPTV Anbieter Abonnements
- Content Improvement League 2024: From Good To A Great Article
Improve your Coding Skills with Practice
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.
Shift array to right in javascript [duplicate]
I have this array:
I need to shift it to right by say 2 locations, like
This works for left shift:
But I don't know how to do shift right...
3 Answers 3
You can use .pop() to get the last item and .unshift() to put it at the front:
Edit : Ten years later, I'm not sure why I originally suggested that brute force approach using a loop. You can do this without a loop by passing a negative number to splice:
Passing a negative number to .splice() removes that many elements from the end of the array and returns them, and .unshift() inserts each argument at the beginning of the array.
Also, for your original shift left code, you can use .push() instead of .concat() and avoid the need to assign the array back to itself.
- 2 would be good to return the array – EugenSunic Commented Nov 3, 2020 at 10:01
- @EugenSunic Returning the array might imply that the function returns a new array that is a shifted copy of the array. By explicitly not returning the array, there's no doubt that this is a mutator function. – gilly3 Commented Feb 13, 2023 at 17:15
Shift to right to N positions == shift to left to array.length - N positions.
So to shift right on 2 positions for you array - just shift it left on 3 positions.
There is no reason to implement another function as soon as you already have one. Plus solutions with shift/unshift/pop in a loop barely will be as efficient as splice + concat
- What if n was greater than the array.length ? – Pete Commented Nov 10, 2019 at 22:24
- @Pete if it's possible then one should implement the check additionally. n = n % array.length – zerkms Commented Nov 10, 2019 at 22:30
Using .concat() you're building a new Array, and replacing the old one. The problem with that is that if you have other references to the Array, they won't be updated, so they'll still hold the unshifted version.
To do a right shift, and actually mutate the existing Array, you can do this:
The unshift() method is variadic, and .apply lets you pass multiple arguments stored in an Array-like collection.
So the .splice() mutates the Array by removing the last two, and returning them, and .unshift() mutates the Array by adding the ones returned by .splice() to the beginning.
The left shift would be rewritten similar to the right shift, since .push() is also variadic:
Not the answer you're looking for? Browse other questions tagged javascript or ask your own question .
- The Overflow Blog
- Mobile Observability: monitoring performance through cracked screens, old...
- Featured on Meta
- Announcing a change to the data-dump process
- Bringing clarity to status tag usage on meta sites
- What does a new user need in a homepage experience on Stack Overflow?
- Staging Ground Reviewer Motivation
- Feedback requested: How do you use tag hover descriptions for curating and do...
Hot Network Questions
- Which version of Netscape, on which OS, appears in the movie “Cut” (2000)?
- Why does my shifter say the wrong gear?
- A strange Lipschitz function
- Could an alien pathogen actually have an effect on us?
- Can an international student email a professor at a foreign university for an internship opportunity?
- How can I use DihedralAngle to get correct result?
- Does an airplane fly less or more efficiently after an mid-flight engine failure?
- In 1982 Admiral Grace Hopper said "I still haven't found out why helicopter rotors go the way they do". If she were here today, how might one answer?
- ESTA is not letting me pay
- Why is simpler prose more popular these days?
- Is the spectrum of Hawking radiation identical to that of thermal radiation?
- My 20 amp breaker trips
- What is the highest apogee of a satellite in Earth orbit?
- If you switch to a non-orthogonal basis, are vectors that were previously orthogonal still orthogonal?
- Duties when bringing Canadian goods to US in luggage
- Took a pic of old school friend in the 80s who is now quite famous and written a huge selling memoir. Pic has ben used in book without permission
- Why race cars accelerate faster than jets?
- How is an inverting opamp adder circuit able to regulate its feedback?
- How to prepare a superposed state?
- What story starts off with the character waking up in a battlefield with wolves and vultures and snow?
- Which Mosaic law was in the backdrop of ceremonial hand-washing in Mark 7?
- How much time would an astronaut experience accelerating to .9999x the speed of light at an acceleration of 1G from the astronauts perspective?
- Reference for proof about a result concerning Sobolev spaces and exponential growth
- Generate vectors with a certain property
![](http://sektorel.online/777/templates/cheerup/res/banner1.gif)
IMAGES
VIDEO
COMMENTS
Right shift assignment (>>=) The right shift assignment ( >>=) operator performs right shift on the two operands and assigns the result to the left operand. x >>= y is equivalent to x = x >> y, except that the expression x is only evaluated once.
The Right Shift Assignment Operator is represented by ">>=".This operator shifts the first operand to the right and assigns the result to the variable. It can also be explained as shifting the first operand to the right in a specified amount of bits which is the second operand integer and then assigning the result to the first operand.
The right shift (>>) operator returns a number or BigInt whose binary representation is the first operand shifted by the specified number of bits to the right. Excess bits shifted off to the right are discarded, and copies of the leftmost bit are shifted in from the left. This operation is also called "sign-propagating right shift" or "arithmetic right shift", because the sign of the resulting ...
The right shift assignment (>>=) operator performs right shift on the two operands and assigns the result to the left operand.
In JavaScript ">>>=" is known as the unsigned right shift assignment bitwise operator. This operator is used to move a particular amount of bits to the right and returns a number that is assigned to a variable.
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 ...
javascript / latest / operators / right_shift_assignment.html. Right shift assignment (>>=) The >>= operator performs right shift on the two operands and assigns the result to the left operand. ... Right_shift_assignment: 1: 12: 1: 3: 1: 18: 4: 10.1: 1: 1.0: 4.4: 1.0: 0.10.0: See also. Assignment operators in the JS guide;
Right shift assignment (>>=) The right shift assignment operator ( >>=) moves the specified amount of bits to the right and assigns the result to the variable. JavaScript Demo: Expressions - Right shift assignment operator. 99.
15. >>> is the unsigned right shift operator ( see p. 76 of the JavaScript 1.5 specification ), as opposed to the >>, the signed right shift operator. >>> changes the results of shifting negative numbers because it does not preserve the sign bit when shifting.
Use the correct assignment operator that will result in x being 15 (same as x = x + y ). Start the Exercise. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.
The >>= operator shifts the bits of result right by the number of bits specified in expression. The sign bit of result is used to fill the digits from the left. Digits shifted off the right are discarded. For example, after the following code is evaluated, temp has a value of -4: 14 (11110010 in binary) shifted right two bits equals -4 ...
The Bitwise right shift assignment operator (>>=) assigns the first operand a value equal to the result of Bitwise right shift operation of two operands. The Bitwise right shift operator (>>) takes the two numbers and right shift the bits of first operand by number of place specified by second operand. For example: for right shifting the bits ...
javascript has 16 different assignment operators that are used to assign value to the variable. It is shorthand of other operators which is recommended to use. Tutorials . HTML5; ... The right shift assignment operator >>= assigns the result of the right shift to the left operand after shifting the value of the left operand by the value of the ...
Assignment operators in the JS guide. Unsigned right shift ( >>>) The >>>= operator performs unsigned right shift on the two operands and assigns the result to the left operand.
Unsigned right shift (>>>) The >>> operator returns a number whose binary representation is the first operand shifted by the specified number of bits to the right. Excess bits shifted off to the right are discarded, and zero bits are shifted in from the left. This operation is also called "zero-filling right shift", because the sign bit becomes ...
Right Shift Assignment(>>=) Operator in JavaScript. The Right Shift Assignment Operator is represented by ">>=". This operator shifts the first operand to the right and assigns the result to the variable. It can also be explained as shifting the first operand to the right in a specified amount of bits which is the second operand integer ...
In JavaScript ">>>=" is known as the unsigned right shift assignment bitwise operator. This operator is used to move a particular amount of bits to the right and returns a number that is assigned to a variable. Syntax: a >>>= b. Meaning: a = a >>> b. Return value: It returns the number after shifting of bits.
The unsigned right shift (>>>) operator returns a number whose binary representation is the first operand shifted by the specified number of bits to the right. Excess bits shifted off to the right are discarded, and zero bits are shifted in from the left. This operation is also called "zero-filling right shift", because the sign bit becomes 0, so the resulting number is always positive ...
Right shift operator (>>), commonly found in programming languages, including C, C++, Java, and others, is used to shift the bits of a number to the right by a specified number of positions. Each shift moves all bits in the operand to the right by the number of positions indicated by the right operand. This comprehensive guide aims to provide a ...
4. Because the return value of this bitwise operation in your JavaScript engine is a signed 32-bit integer that can only represent numbers from -2147483648 to 2147483647. The control of whatever an integer is negative or positive is done by setting the signal bit, the bit of highest relevance in the 32-bits chain (2^31).
Shift to right to N positions == shift to left to array.length - N positions. So to shift right on 2 positions for you array - just shift it left on 3 positions. There is no reason to implement another function as soon as you already have one. Plus solutions with shift/unshift/pop in a loop barely will be as efficient as splice + concat