1

Can someone please explain in details why (-3>>0).toString(2) doesn't return two's complement of 3 in the binary form 11111111111111111111111111111101, whereas (-3>>>0).toString(2) returns does?

Both use bit shift, but the former uses Sign-propagating right shift and latter uses Zero-fill right shift. I've found this explanation:

-3 >>> 0 (right logical shift) coerces its arguments to unsigned integers, which is why you get the 32-bit two's complement representation of -3.

But I don't know what to make of it. Please provide elaborate answer if possible.

Max Koretskyi
  • 85,840
  • 48
  • 270
  • 414
  • 4
    This has nothing to do with twos-complement. It's just `-3>>>0 == 4294967293` vs `-3>>0 == -3` – Bergi May 03 '16 at 18:22
  • 1
    Possible duplicate of [What is the JavaScript >>> operator and how do you use it?](http://stackoverflow.com/questions/1822350/what-is-the-javascript-operator-and-how-do-you-use-it) – freakish May 03 '16 at 18:23
  • @Bergi, still not clear :(. can you please elaborate? – Max Koretskyi May 03 '16 at 18:28
  • Umm, why do you care about this? –  May 03 '16 at 19:16
  • @torazaburo, what do you mean? :) – Max Koretskyi May 03 '16 at 19:24
  • @Maximus: The `>>>` operator casts its operand to an unsigned 32 bit integer. `-3` corresponds to `4294967293` - it's just modulo 2^32. – Bergi May 03 '16 at 20:07
  • @Bergi, so what you're saying is that Javascript stores `-3` internally in the binary form `11111111111111111111111111111101`, but then when I use `>>>` operator Javascript simply takes that form and treats it as an unsigned integer? – Max Koretskyi May 04 '16 at 07:03
  • 1
    @Maximus: No, `-3` is stored as a double, as every number in JS. It's just converted to that unsigned integer [using the algorithm](http://www.ecma-international.org/ecma-262/6.0/#sec-touint32) when the `>>>` operator is used on it. – Bergi May 04 '16 at 13:00
  • @Bergi, I see now, thanks a lot! It'd be great if you posted a small summary as an answer so that I can accept it – Max Koretskyi May 05 '16 at 07:03

1 Answers1

0

it seems that >> just lefts the same sign while bitwise operation is made over absolute value:

var absValue = Math.abs(value), 
    sign = value / absValue;
value = sign * (Math.abs(value) >> base);

So there is not difference for positive/negative values, they are operated equally but saves their sign.

While >>> operates on full value(including complement forms for negative values) just by treating value as unsigned but not actual converting it.

skyboyer
  • 15,149
  • 4
  • 41
  • 56