简体   繁体   中英

javascript bitwise xor producing inconsistent result

I am using bitwise operations in javascript but I have noticed something that appears inconsistent.

Right now, I'm using the XOR (^) operation. When I do '0101'^'0001' , I get 4, which makes sense since 4 = 0100 in binary. But when I do '10001'^'01111' , I get 9030, when I think I should get 11110. The format is, to best that I can tell, the same; only the strings are different.

console.log(5^1); //4
console.log('0101'^'0001'); // 100 = 4

console.log(17^15); //30
console.log('10001'^'01111'); //9030...why? shouldn't it be '11110'?

Why is this code producing this result?

Now, If I do this:

console.log(('0b'+'10001')^('0b' + '01111')); //30

Why did I have to add '0b' to specify that the strings were binary sequences when doing bitwise ops on 17 and 15, but not with 5 and 1?

You are using the ^ operator on strings. When using any numerical operator on a string JavaScript will implicitly convert the string to a number. Adding 0b tells JavaScript to treat your number as a binary or base 2 number.

Otherwise, by default they will be converted to decimal or base 10 values.

Do operations on binary values represented in a string you have to convert your values to numerical base 2 values first.

You can verify in a calculator 10,001^1111 = 9030.

In binary 1111=15 and 10001=17. 15^17= 30 which is 11110‬ in binary.

101 Xor 1 is a special case, In decimal 101 Xor 1 = 100. In Binary 101 = 5 and 5 Xor 1 = 4 which is written out in binary as 100.

As has been pointed out already, you are not using binary numbers. Use the 0b prefix for binary numbers and toString(2) to convert back:

console.log((0b10001 ^ 0b01111).toString(2));
11110

The first example just works because 1 in decimal is the same as 1 in binary. The result is 100 (decimal) though, not 4. Javascript doesn't store the number format internally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM