Random code: Super efficient binary counter

For some mad reason I decided to try and see how efficient I could code a binary counter. Assume you have n LEDs, which are represented as ints: 0 = off, 1 = on. You also have a counter variable: int counter; I ended up with a few bitshifts, addition and logic ANDs. Here is my code:

LED1 = (counter >> 0) & 1;
LED2 = (counter >> 1) & 1;

LEDn = (counter >> (n-1)) & 1;

/* Equivalent to: counter = (counter+1) % pow(2,n) */
counter = (++counter) & ((1 < < n)-1)

1 comment so far ↓

#1 Ashley on 12.25.06 at 1:36 am

Merry Christmas and Happy New Year. Great Blog!

Leave a Comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image