HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Running a block of code on every interval except the first iteration

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theblockintervaleveryiterationrunningfirstcodeexcept

Problem

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  0 && (i % 4 == 0)) {
      key *= 13
   }

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


What I don't like is that check for i > 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 > 0 checks when i is always increasing.

Solution

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 > 0) {
    data[0] ^= key;
}
for (int i = 1; i > (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 > (   0);
   data[i + 1] ^= key >> (   8);
   data[i + 2] ^= key >> (  16);
   data[i + 3] ^= key >> (  24);

   key *= 13

}

// handle up to 3 remaining bytes.....
for (int i = dataSize - (dataSize & 3); i > (8 * (i & 3));
}

Code Snippets

if (dataSize > 0) {
    data[0] ^= key;
}
for (int i = 1; i < dataSize; i++) {

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

   // Shift over i bytes, as per the algorithm
   data[i] ^= key >> (8 * (i % 4));
}
for (int i = 0; i < dataSize - 3; i+=4) {

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

   key *= 13

}

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

Context

StackExchange Code Review Q#36875, answer score: 6

Revisions (0)

No revisions yet.