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

Bitwise XOR operator in JavaScript

Why is this:

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

Please explain. Thanks.

+8
javascript bit-manipulation
source share
1 answer

These numbers are interpreted as decimal numbers.

Try:

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

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

JavaScript marker grammar supports numbers in decimal, octal, and hexadecimal, but not binary. Thus:

 console.log(0xC0 ^ 0x09) 

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

+11
source share

All Articles