Search code examples
c++xor32-bit8-bit

C++ Convert XOR Implementation To 8 Bit (Processor Doesn't Support XOR)


This function is used to calculate the XOR of a 32 bit integer

int xor32int(int x, int y)
{
    int res = 0; // Initialize result 

    // Assuming 32-bit Integer  
    for (int i = 31; i >= 0; i--)
    {
        // Find current bits in x and y 
        bool b1 = x & (1 << i);
        bool b2 = y & (1 << i);

        // If both are 1 then 0 else xor is same as OR 
        bool xoredBit = (b1 & b2) ? 0 : (b1 | b2);

        // Update result 
        res <<= 1;
        res |= xoredBit;
    }
    return res;
}

This works fine when XOR'ing 8 bit values, but they first need to be casted to int, i.e.

char byte1 = 0x23, byte2 = 0x34;
int result = xor32int((int)byte1, (int)byte2);

And being that xor32int() assumes input to be 32 bit integers it runs a loop 32 times, so even if value is only 8 bit it runs extra loops when unnecessary resulting in a major decrease in performance.

How would I go about converting the xor32int() function so it only works with 8 bit values so it doesn't need to loop 32 times?

If you are wondering why don't I simply use the XOR operator, it is because I am working with an old machine that uses a processor that doesn't support XOR.


Solution

  • Is there a reason you can't use (x | y) & ~(x & y)? That's one definition of xor. You can write it as a function:

    char xor8(char x, char y) {
        return (x | y) & ~(x & y);
    }
    

    You can even write it as a function template:

    template<typename T>
    T xorT(T x, T y) {
        return (x | y) & ~(x & y);
    }
    

    In case you can't use that for some reason, I'm pretty sure you can replace int with char, and 31 with 7:

    char xor8char(char x, char y)
    {
        char res = 0;
    
        for (int i = 7; i >= 0; i--)
        {
            bool b1 = x & (1 << i);
            bool b2 = y & (1 << i);
    
            bool xoredBit = (b1 & b2) ? 0 : (b1 | b2);
    
            res <<= 1;
            res |= xoredBit;
        }
        return res;
    }
    

    All of that, live on Coliru.