Running a block of code on every interval except the first iteration I am working with an encryption algorithm that looks like this


The key is a number stored in 4 bytes.
For each byte in the message, XOR it with the corresponding byte in the key
When you reach the end of the key, multiply the key by 13, and then continue looping


Translated, it looks like this

for (int i = 0; i &lt; dataSize; i++) {

   // Increase the key as per the algorithm
   if (i &gt; 0 &amp;&amp; (i % 4 == 0)) {
      key *= 13
   }

   // Shift over i bytes, as per the algorithm
   data[i] ^= key &gt;&gt; (8 * (i % 4));
}


What I don't like is that check for i &gt; 0, as it looks like wasteful processing. How can I modify this code so that I don't have that extra check that is basically redundant after the first iteration of the loop?

If the size of the data is 5 MB I don't want to run an extra 5 million or so i &gt; 0 checks when i is always increasing.
Initialize the first byte, and then start the loop from 1.....

You may also want to do a bit-check instead of modulo, but they may be equally fast...

if (dataSize &gt; 0) {
    data[0] ^= key;
}
for (int i = 1; i &lt; dataSize; i++) {

   // Increase the key as per the algorithm
   if (i &amp; 3 == 0) {
      key *= 13
   }

   // Shift over i bytes, as per the algorithm
   data[i] ^= key &gt;&gt; (8 * (i % 4));
}


EDIT:

I have seen the following done (translating from memory of a C program)... this has been known to be able to compile down to SIMD-using instructions on supporting compilers, etc.

for (int i = 0; i &lt; dataSize - 3; i+=4) {

   // Shift over i bytes, as per the algorithm
   data[i + 0] ^= key; // &gt;&gt; (   0);
   data[i + 1] ^= key &gt;&gt; (   8);
   data[i + 2] ^= key &gt;&gt; (  16);
   data[i + 3] ^= key &gt;&gt; (  24);

   key *= 13

}

// handle up to 3 remaining bytes.....
for (int i = dataSize - (dataSize &amp; 3); i &lt; dataSize; i++) {
    data[i] ^= key &gt;&gt; (8 * (i &amp; 3));
}