The pages before this one inspect a number. This one constructs one, bit by bit. The loop shape is the same every time: peel the lowest bit off the input, decide what the output bit should be, shift it into place, repeat.
That shape is worth internalizing, because it is also how the hardware works. A full adder is exactly this loop with one extra piece of state - the carry.
Flipping every bit within the number's own width is the tricky part: Python integers are conceptually infinite, so a bare ~n gives you a negative number, not a complement. Build an all-ones mask of the right width and XOR against that instead. Reversing mirrors bit positions rather than flipping values, and its greedy cousin asks for the cheapest way to reach a palindrome.
An encoding is a bijection between an index and a bit string. Find the pattern - usually "the binary of n + 1 with its leading 1 stripped" - and the answer is a slice, not a search. The reverse direction subtracts a chosen popcount from a value until nothing is left.
Simulate what + does internally. a ^ b is the sum with all carries ignored; (a & b) << 1 is exactly those carries, shifted into the column they belong to. Loop until the carry is zero. Doing the same on strings is the schoolbook version of the identical circuit.