Javascript Bitwise Operator Unsigned Right Shift

Introduction

The unsigned right shift is represented by three greater-than signs (>>>) and shifts all bits in a 32-bit number to the right.

For numbers that are positive, the effect is the same as a signed right shift.

If 64 is shifted to the right five bits, it becomes 2:

let oldValue = 64;              // equal to binary 1000000 
let newValue = oldValue >>> 5;  // equal to binary 10 which is decimal 2 

Unlike signed right shift, the empty bits get filled with zeros regardless of the sign of the number.

For positive numbers, it has the same effect as a signed right shift.

For negative numbers, the result is different.

The unsigned-right-shift operator considers the binary representation of the negative number to be representative of a positive number instead.

Because the negative number is the two's complement of its absolute value, the number becomes very large:

let oldValue = -64;             // equal to binary 11111111111111111111111111000000 
let newValue = oldValue >>> 5;  // equal to decimal 134217726 

When an unsigned right shift is used to shift -64 to the right by five bits, the result is 134217726.

The binary representation of -64 is 11111111111111111111111111000000, but because the unsigned right shift treats this as a positive number.

It considers the value to be 4294967232.

When this value is shifted to the right by five bits, it becomes 00000111111111111111111111111110, which is 134217726.




PreviousNext

Related