Is it legal to >>> 0 in order to keep bitwise operations as unsigned 32-bit?

1

For example, this is -1 a.k.a. 0xFFFFFFFF as a signed 32-bit:

0xFFFFF000 | 0xFFF

However, this is this is 4294967295 a.k.a. 0xFFFFFFFF as an unsigned 32-bit:

(0xFFFFF000 | 0xFFF) >>> 0

Can I rely on using this >>> 0 trick to keep my bitwise operations as unsigned 32-bit?

Nothing in the spec[1] indicates that this should fail, and it seems to work fine in a few simple tests...

[1] https://www.ecma-international.org/ecma-262/9.0/index.html#sec-unsigned-right-shift-operator

javascript
asked on Stack Overflow Aug 21, 2019 by davidkomer • edited Aug 21, 2019 by davidkomer

1 Answer

2

According to MDN (emphasis mine):

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. The sign bit becomes 0, so the result is always non-negative. Unlike the other bitwise operators, zero-fill right shift returns an unsigned 32-bit integer.

So it sounds like you can count on that always working.

Also from the ECMAScript specs Section 12.9.5.1 #8 (again emphasis is mine):

Return the result of performing a zero-filling right shift of lnum by shiftCount bits. Vacated bits are filled with zero. The result is an unsigned 32-bit integer.

answered on Stack Overflow Aug 21, 2019 by c1moore • edited Aug 22, 2019 by c1moore

User contributions licensed under CC BY-SA 3.0