8

Why is this:

console.log("1100" ^ "0001")
=> 1101 // as expected

console.log("1100" ^ "1001")
=> 1957 // ???

Please explain. Thanks.

1
  • You are using the XOR operator, but actually you seem to want the OR, since for 1101 | 0001 = 1101 (OR), while 1101 ^ 0001 = 0101 (XOR). Commented Mar 31, 2012 at 14:17

1 Answer 1

11

Those numbers are interpreted as decimal numbers.

Try:

console.log(parseInt("1100", 2) ^ parseInt("1001", 2))

Of course the answer (0101) is printed in decimal (5).

The JavaScript token grammar supports numbers in decimal, octal, and hex, but not binary. Thus:

console.log(0xC0 ^ 0x09)

The first one worked, by the way, because 1100 (decimal) is 1101 (decimal) after the xor with 1.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.