What does bitwise XOR (exclusive OR) mean?

前端 未结 8 1234
眼角桃花
眼角桃花 2020-12-02 05:52

I\'m trying to understand the binary operators in C# or in general, in particular ^ - exclusive or.

For example:

Given an array of positive intege

8条回答
  •  有刺的猬
    2020-12-02 06:31

    The other way to show this is to use the algebra of XOR; you do not need to know anything about individual bits.

    For any numbers x, y, z:

    XOR is commutative: x ^ y == y ^ x

    XOR is associative: x ^ (y ^ z) == (x ^ y) ^ z

    The identity is 0: x ^ 0 == x

    Every element is its own inverse: x ^ x == 0

    Given this, it is easy to prove the result stated. Consider a sequence:

    a ^ b ^ c ^ d ...

    Since XOR is commutative and associative, the order does not matter. So sort the elements.

    Now any adjacent identical elements x ^ x can be replaced with 0 (self-inverse property). And any 0 can be removed (because it is the identity).

    Repeat as long as possible. Any number that appears an even number of times has an integral number of pairs, so they all become 0 and disappear.

    Eventually you are left with just one element, which is the one appearing an odd number of times. Every time it appears twice, those two disappear. Eventually you are left with one occurrence.

    [update]

    Note that this proof only requires certain assumptions about the operation. Specifically, suppose a set S with an operator . has the following properties:

    Assocativity: x . (y . z) = (x . y) . z for any x, y, and z in S.

    Identity: There exists a single element e such that e . x = x . e = x for all x in S.

    Closure: For any x and y in S, x . y is also in S.

    Self-inverse: For any x in S, x . x = e

    As it turns out, we need not assume commutativity; we can prove it:

    (x . y) . (x . y) = e  (by self-inverse)
    x . (y . x) . y = e (by associativity)
    x . x . (y . x) . y . y = x . e . y  (multiply both sides by x on the left and y on the right)
    y . x = x . y  (because x . x = y . y = e and the e's go away)
    

    Now, I said that "you do not need to know anything about individual bits". I was thinking that any group satisfying these properties would be enough, and that such a group need not necessarily be isomorphic to the integers under XOR.

    But @Steve Jessup proved me wrong in the comments. If you define scalar multiplication by {0,1} as:

    0 * x = 0
    1 * x = x
    

    ...then this structure satisfies all of the axioms of a vector space over the integers mod 2.

    Thus any such structure is isomorphic to a set of vectors of bits under component-wise XOR.

提交回复
热议问题