I have the following code implement a shift action of a linear feedback shift register:
public int DoShift()
{
//Find new top bit
int feedback = Contents & tapSequence;
int newBit = 0;
for(int i = 1; i <= length; i++)
{
newBit = 1 & (newBit ^ feedback);
feedback >>= 1;
}
//Remember falloff, shift register, add new bit
int result = Contents & 1;
Contents >>= 1;
Contents += newBit << (length - 1);
return result;
}
where
- Contents is the current contents of the register
- tapSequence is the XOR tap sequence, where a 1 represents a tapped bit and a 0 represents an untapped bit.
- length is the number of bits the register has.
However, having run a CPU usage test, this function takes up as much as 60% of my runtime (for what I thought would've been a fairly lightweight method). Is there a more efficient way to write this? Is there a way to XOR the contents of an int with its own bits (so as to do away with the for loop)?
forloop early? Change it to awhileloop somehow? - BrannonnewBitis basically the parity offeedback. Take a look here to find some alternatives to the loop. Btw, the lastContents +=can be expressed as a bitwise OR becausenewBitis just one bit. - Nico Schertlerfeedback == 0, I'll add that. Why would changing to a while loop help? - LeftRight92Contents = Contents ^ (newBit << (length - 1))be more efficient then? - LeftRight92