0

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 (i.e. most significant bit always 1 in both case), I get different outputs, what am I missing?

Thanks

kaushal
  • 691
  • 7
  • 26
  • What makes you think that the output should be unsigned? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators – Felix Kling Oct 09 '14 at 15:11
  • Because as per the definition of >>> it shifts in zeroes from left. And in the '&' operation I am explicitly clearing the most significant sign bit. – kaushal Oct 09 '14 at 15:18
  • Btw, this question has some more details about the >>> operator. http://stackoverflow.com/questions/1822350/what-is-the-javascript-operator-and-how-do-you-use-it – kaushal Oct 09 '14 at 15:23
  • What are the outputs? – punstress Dec 28 '14 at 05:45

1 Answers1

1

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.

jeffpar
  • 36
  • 3