rockford98 - 6 months ago 21

Javascript Question

I am trying to understand Javascript logical operators and came across 2 statements with seeminlgy similar functionality and trying to understand the difference. So, What's the difference between these 2 lines of code in Javascript?

For a number x,

`x >>>= 0;`

x &= 0x7fffffff;

If I understand it correctly, they both should give unsigned 32 bit output. However, for same negative value of

`x`

Thanks

Answer

To truncate a number to 32 bits, the simplest and most common method is to use the "|" bit-wise operator:

```
x |= 0;
```

JavaScript always considers the result of any 32-bit computation to be negative if the highest bit (bit 31) is set. Don't let that bother you. And don't clear bit 31 in an attempt to make it positive; that incorrectly alters the value.

To convert a negative 32-bit number as a positive value (a value in the range 0 to 4294967295), you can do this:

```
x = x < 0? x + 0x100000000 : x;
```

By adding a 33-bit value, automatic sign-extension of bit 31 is inhibited. However, the result is now outside the signed 32-bit range.

Another (tidier) solution is to use the unsigned right-shift operator with a zero shift count:

```
x >>>= 0;
```

Technically, all JavaScript numbers are 64-bit floating-point values, but in reality, as long as you keep numbers within the signed 32-bit range, you make it possible for JavaScript runtimes to optimize your code using 32-bit integer operations.

Be aware that when you convert a negative 32-bit value to a positive value using either of above methods, you have essentially produced a 33-bit value, which may defeat any 32-bit optimizations your JavaScript engine uses.

Source (Stackoverflow)

Comments