0

My discrete math tells me that negate every bit of a binary number is equivalent to XOR it with 1. That is:

~1010 === 0101
1010 XOR 111 = 0101

But this doesn't hold in javascript:

~123 === -124
123 ^ 1 === 122

Why?

4

1 回答 1

2

1 is not binary 111

Negating every bit of a number is equivalent to XOR every bit with 1, i.e., with a number of equal size where all bits are 1.

For a single byte, you'd want to xor with binary 11111111 which equals to decimal 255, not 1. Decimal 1 is binary 00000001, so in a bitwise XOR you're flipping only the last bit.

于 2017-01-21T21:22:11.297 回答