One of the keys is that rotary the bits go through what's known as a gray code. Only one bit changes at a time.
So with two bits, one direction will look like 00 -> 01 -> 11 -> 10 -> 00 ....
and the other direction will just be the above in reverse. This article has a good explanation:
https://lastminuteengineers.com/rotary- ... -tutorial/
and here's a good youtube video with some nice animations:
https://www.youtube.com/watch?v=v4BbSzJ-hz4
And this one talks about debouncing:
https://www.allaboutcircuits.com/projec ... d-project/