Jump to content
  • Advertisement
Sign in to follow this  
Headkaze

Xor and xnor confusion

This topic is 2506 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!