I need to take an 8 bit number on a 64 bit cpu and shift it to the right 8 times. Each time I shift the number I need to shift the same 8 bit number in behind it so that I end up with the same 8 bit number repeating 8 times. This would end up being shift, add 8, shift add 8… etc. which ends up being 40+ cycles (correct me if I’m wrong).
Is there a way to do this operation (of shift and copy) in 1 cycle so that I end up with the same value in the end?
long _value = 0;
byte _number = 7;
for (int i = 0; i < 8; i++) {
_value = (_value << 8) + _number;
}
EDIT: I’m trying to compare a stream of chars to detect keywords. I can’t use string.contains because the string value may be across the boundary of the buffer. Also, the application has to run on embedded ARM cpus as well as desktop and server CPUs. Memory usage and cpu cycles are very important.
Another idea would be to precompute all for all values of byte a lookup table.
Update
Some benchmark results (in ms per 100000000 iterations):
The unrolled version is:
The unsafe version is:
Sadly not performing 🙁
The lookup is just a read to an array.
All compiled for x64/release.