LFSR Programming question-:?
I could not understand this text, can you elaborate?-:
Extracting multiple bits. The member function generate() takes an integer k as an argument and returns a k-bit integer obtained by simulating k steps of the LFSR. This task is easy to accomplish with a little arithmetic: initialize a variable to zero and, for each bit extracted, double the variable and add the bit returned by step(). For example, if the first 5 bits extracted are 1, then 1, then 0, then 0, then 1, the variable takes on the values 1, 3, 6, 12, and 25, which is the binary representation of the bit sequence 11001. For example,...
- husoskiLv 71 month agoFavorite Answer
It's pretty straightforward. The generate(k) function should initialize a result variable to 0; then loop k times, shifting in a bit value from step() each time. That "shift" is just:
result = 2*result + step();
...assuming step() always returns a 0 or 1. You can write that in other ways:
result = (result << 1) | step(); // explicitly shift, then or the low bit
result = result + result + step(); // use addition instead of multiplication
result += result; result += step(); // double then add in low bit in 2 statements
Pick whichever you like, but the first literally follows what the text said to do. I trust you already know how to loop exactly k times.