The other day I’ve learnt a cool trick in Verilog. When you need to do something repeatedly. You could use a shift register to count the number of incrementation. Just shifting a 1 from LSB to MSB, and when it reach the MSB you’re done.
In C it would be something like this:
for(j=0b1; !(j & (1<<16)); j=j<<1)
{
/*do a thing 16 times*/
}
I know it has limited use because of the bit width, but it isn’t involving any addition so it is fast.
So my question: Is there any use of this? Is it worth it to use in C or any other high-level language?
Maybe in embedded systems where resources are limited.
Thanks
For which CPU architecture is shift faster than addition? Also, what makes you think the compiler for that specific architecture wouldn’t do the optimization from addition to shift automatically, if it would turn out that shift is faster?
For optimization purposes, no there isn’t any use of it.
For other purposes, yes, code like that is commonly used for masking out individual bits of a byte. I believe the two most common approaches are these:
or