简体   繁体   中英

bitwise negate and bitwise XOR 1 not equivalent?

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?

1 is not binary 111

Negating every bit of a number is equivalent to XOR every bit with 1, ie, 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.

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