Search code examples
mathguidxor

Does the result of combining two GUIDs via XOR satisfy the conditions of being a GUID?


Given two GUIDs, A and B, I perform C = A ^ B. Is the result a GUID?

(If so, I can use that instead of generating a third guid to represent an object that contains the two objects represented by A and B.)


Solution

  • A GUID is nothing but a uniform random number in the range of 0 to 2128 - 1. From a theoretical perspective, there is nothing which guarantees they are ever unique, but as this question keenly demonstrates, GUIDs are unique in practice due to the extremely low likelihood of a collision.

    Given that there are only two requirements to meet: 1) range and 2) uniform randomness, it is easy to prove that the XOR of two GUIDs is indeed a GUID.

    Imagine if GUID's were only two bits, then we can examine all possible scenarios:

     ^  00  01  10  11
    00  00  01  10  11
    01  01  00  11  10
    10  10  11  00  01
    11  11  10  01  00
    

    All possible results 1) have the same range of 00 to 11, and 2) are equally likely to occur.

    The only exception to this rule would be if one of the two source GUIDs is all zeros, causing the resulting XOR to produce a collision with the other.

    Note that XOR is not the only operation to have this ability - adding two GUIDs and truncating the overflow bit also produces a GUID.


    I wanted to amend clarification regarding UUID/GUID specifications which include a number of fixed bits.

    Although there is no official, single definition of a "GUID", it conventionally is assumed to mean an RFC4122 UUID v4.

    In the specification, all bits are random except:

    • 4 most-significant bits of byte 7 are 0100
    • 2 most-significant bits of byte 9 are 10

    Performing an XOR on two UUIDv4's will not create another UUIDv4 unless you reset those bits as a post operation:

    C = (A ^ B) & ffffffff-ffff-0fff-3fff-ffffffffffff | 00000000-0000-4000-8000-000000000000
    

    With this adjustment, the result C will be a well-formed GUID as commonly defined.

    Summary

    I still stand by the original answer, but with some clarification:

    The XOR of the random bits of two GUIDs results in a GUID.