Mathematical (Arithmetic) representation of XOR

前端 未结 8 1050
一向
一向 2021-02-04 07:27

I have spent the last 5 hours searching for an answer. Even though I have found many answers they have not helped in any way.

What I am basically looking for is a mathem

8条回答
  •  温柔的废话
    2021-02-04 08:19

    I do realize that this is sort of an old topic, but the question is worth answering and yes, this is possible using an algorithm. And rather than go into great detail about how it works, I'll just demonstrate with a simple example (written in C):

        #include 
        #include 
        #include    
        #include 
    
        typedef unsigned long
                number;
    
        number XOR(number a, number b)
        {
                number
                        result = 0,
                /*
                        The following calculation just gives us the highest power of 
                        two (and thus the most significant bit) for this data type.
                */          
                        power = pow(2, (sizeof(number) * 8) - 1);
        /*
                Loop until no more bits are left to test...
        */                
                while(power != 0)
                {
                        result *= 2;
                /*
                        The != comparison works just like the XOR operation.
                */                
                        if((power > a) != (power > b))
                                result += 1;
                        a %= power;
                        b %= power;
                        power /= 2;
                }
                return result;
        }
    
        int main()
        {
                srand(time(0));
                for(;;)
                {
                        number
                                a = rand(), 
                                b = rand();
                        printf("a = %lu\n", a);
                        printf("b = %lu\n", b);
                        printf("a ^ b     = %lu\n", a ^ b);
                        printf("XOR(a, b) = %lu\n", XOR(a, b));
                        getchar();
                }
        }
    

提交回复
热议问题