0

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.

Power5
  • 69
  • 1
  • 5
  • you have & operator but not ^ ? not sure I understand the problem – OznOg Oct 28 '18 at 10:51
  • @OznOg Yes, certain CPUs don't support XOR, but they do support AND, OR, etc.. But that's besides the question. This question is simply asking how would I go about taking the `xor32int()` function, and changing it so it assumes 8 bit input rather than 32 bit input. – Power5 Oct 28 '18 at 10:57
  • Can't you just change `31` to `7`? (also it is better to use *unsigned* types with bit manipulations) – Galik Oct 28 '18 at 11:02

1 Answers1

2

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.

Nelfeal
  • 12,593
  • 1
  • 20
  • 39