Search code examples
c++arraysxor

XOR and Shifting bits in array


I have an array that holds a 16-bit value with each bit in an array index. What I want to do is perform a "bit-wise" XOR of particular array elements and then shift all the elements over by 1 (with wrapping).

In particular, I want to use XOR at the array elements 2, 3, and 5 with last element, 16.

This code is supposed to be cyclic, such that once it has completed a particular number of cycles (65535), it should return to the original input value.

Here is my code:

#include <iostream>
using namespace std;

void main()
{
    //Initial array input
    int state_array[16] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 };
    int temp[1] = { 0 };

    int array_size = sizeof(state_array) / (sizeof(temp[0]));

    for (int i = 0; i<65535; i++)
    {
        temp[0] = state_array[15];

      //XOR Values
        for (int j = 0; j<16; j++) {
            if ((j == 2 || j == 3 || j == 5) && state_array[15] == 1) {
                state_array[j] = !state_array[j];
            }
        }

        //Shift values
        for (int j = array_size-1; j>0; j--)
        {
            if (j == 0) {
                state_array[0] = temp[0];
            }
            else {
                state_array[j] = state_array[j-1];
            }
        }
    }
}

What should happen is that after 65535 iterations, the array returns back to value 0000000000000001, but this does not happen and I cannot figure out why. I feel like its a small, obvious thing I am overlooking in my code but, I can't figure it out.


Solution

  • The issue is that you're not indexing correctly. Instead of your statement that does the XORing looking like this:

    if ((j == 2 || j == 3 || j == 5) && state_array[15] == 1) {
        state_array[j] = !state_array[j];
    }
    

    it needs to be 0-indexed, not 1, and should look like this:

    if ((j == 1 || j == 2 || j == 4) && state_array[15] == 1) {
        state_array[j] = !state_array[j];
    }
    

    Ironically, your state_array[15] was correct, it's just 2, 3, and 5 that need to be fixed.

    Additionally, your for loop should have the condition j>=0 not just j>0.