Jump to content



Xor and xnor confusion

  • You cannot reply to this topic
3 replies to this topic

#1 Headkaze   Members   -  Reputation: 422

Like
0Likes
Like

Posted 03 February 2012 - 08:36 AM

I have a struct that I want to xor with a key before saving and then xnor back after loading.

For some reason the first xor and xnor does not produce the original results. But an additional call will. The problem appears to be related to the sign bit.

Here are the two functions

void XOR(unsigned char *data, unsigned int length, const string& key)
{
    for (int k = 0, v = 0; v < length; v++)
    {
        data[v] = data[v] ^ key[k];
        k = (++k < key.length() ? k : 0);
    }
}

void XNOR(unsigned char *data, unsigned int length, const string& key)
{
    for (int k = 0, v = 0; v < length; v++)
    {
        data[v] = ~(data[v] ^ key[k]);
        k = (++k < key.length() ? k : 0);
    }
}

And here are some tests

DEBUGLOG("1. %d", g_settings.Size);
   
XOR((unsigned char *)&g_settings, sizeof(Settings), KEY);
    
DEBUGLOG("2. %d", g_settings.Size);
    
XNOR((unsigned char *)&g_settings, sizeof(Settings), KEY);
    
DEBUGLOG("3. %d", g_settings.Size);
    
XOR((unsigned char *)&g_settings, sizeof(Settings), KEY);
    
DEBUGLOG("4. %d", g_settings.Size);
    
XNOR((unsigned char *)&g_settings, sizeof(Settings), KEY);
    
DEBUGLOG("5. %d", g_settings.Size);

The output I'm getting is

1. 1224
2. 977354226
3. -1225
4. -977354227
5. 1224


Ad:

#2 Cornstalks   Members   -  Reputation: 1215

Like
0Likes
Like

Posted 03 February 2012 - 08:41 AM

You'll have to think about how the logic works with XOR. Forget XNOR. original == (original ^ key) ^ key == original ^ (key ^ key) == original ^ (0) == original.

To load and save you should just use XOR.
[ Realistic Rendering ] [ School + Dublin = Boom ] [ I've been ninja'd 70 times ] [ f.k.a. MikeTacular ] [ My Blog ]

#3 Antheus   Members   -  Reputation: 2303

Like
0Likes
Like

Posted 03 February 2012 - 08:46 AM

The opposite of XOR is XOR.

#4 Headkaze   Members   -  Reputation: 422

Like
0Likes
Like

Posted 03 February 2012 - 08:55 AM

That might explain it. Thanks guys.






We are working on generating results for this topic
PARTNERS