I recently came across a strange piece of code that uses the >>>=
operator (I'll show it later in the question).
The >>>
is the unsigned right bit shift operator, as mentioned in What is the JavaScript >>> operator and how do you use it?
The mozilla documentation describes the operator as...
a >>> b
shiftsa
in binary representationb
(< 32) bits to the right, discarding bits shifted off, and shifting in zeroes from the left.
Given this knowledge, I have assumed that >>>=
is the in-place unsigned right bit shift operator.
The strange piece of code
Remember that piece of code I mentioned at the start? Here it is...
(number) => {
number >>>= 0;
// Do stuff with number...
}
I'm very curious as to why someone would perform an in-place bit shift with 0
.
What are the use-cases?
The attempt to find use-cases
In an attempt to answer my question, I wrote a quick script that would iterate through all unsigned 32-bit integers and compare the integer to its (unsigned right shifted by 0) counterpart.
"use strict";
const assertEqual = (a, b, message) => {
if (a !== b) {
throw message
}
}
const START = 0
const END = Math.pow(2, 32) - 1
for (let n = START; n < END; n++) {
let nShifted = n
nShifted >>>= 0
const message = n + " !== (" + n + " >>>= 0) (which is " + nShifted + ")"
assertEqual(n, nShifted, message)
}
console.log("done.")
As expected, the program finished with no exceptions, since bit-shifting by 0 will have no effect.
This, however, would throw an exception if any of the values were negative.
More experimenting
It appears that performing the shift truncates the result into a 32-bit integer, which isn't surprising.
It also appears that when shifting negative integers, the result is the two's complement, which makes sense because it's making the value unsigned.
For example...
x = -1
console.log(x.toString(2)) // '-1'
x >>>= 0
console.log(x.toString(2)) // '11111111111111111111111111111111'
// (Two's complement of -1)
- As mentioned in the comments, using the operator on floating-point numbers will truncate the decimal section and result in an integer.
For example...
x = 2.6
x >>>= 0
console.log(x) // '2'
Summary
In-place right shifting by 0 an integer will truncate it to 32 bits and make it unsigned.
Are there any other use cases for this?