0

I experimented with the bitwise-operator suggested to my question and here.

Check the results of my testsuite:

function equal(n1,n2){
    var bool = (n1^n2 >= 0)?true:false;
    document.write("<div>"+bool+" ("+(n1^n2)+")</div>");
}


equal(-5,-2);  //true
equal(-4,-20); //true
equal(15,-2);  //false
equal(25,3);   //true 

equal(-1,1);   //false
equal(1,1);    //true
equal(-1,-1);  //true

// edgecases
equal(0,0);
equal(-0,0);
equal(+0,0);
equal(-0,+0);
equal(+0,-0);

outcome:

true (5)
true (16)
true (-15)
true (26)

true (-2)
false (0)
true (0)

true (0)
true (0)
true (0)
true (0)
true (0)

My according fiddle is here.

The result confuses me very much. Am I too stupid? What has happened here?

Community
  • 1
  • 1
Christoph
  • 50,121
  • 21
  • 99
  • 128
  • You're not stupid, Javascript has some really interesting behavior with numbers approaching zero. Read this: http://www.2ality.com/2012/03/signedzero.html – Mike Robinson Apr 24 '12 at 15:07

1 Answers1

1

You had your parentheses in the wrong place:

function equal(n1, n2){
    var bool = (n1 ^ n2) >= 0 ? true : false;
    document.write("<div>" + bool + " (" + (n1^n2) + ")</div>");
}

Here's an updated fiddle with results matching what you expect.

This is important in this case because all of the bitwise operators are of lower precedence than the relational comparison operators. Also note that the conditional operator (?:) is of lower precedence than all of the bitwise operators, so there's no need for another set of parentheses around the entire condition.

James Allardice
  • 164,175
  • 21
  • 332
  • 312