dc, 66 bytes
Try it online!
[2~rd0<B]dsBx is a macro that uses
dc's quotient/remainder integer division,
~ to continuously break divide by two, breaking n down to individual binary bits on the stack. It will always leave one extra zero, so we subtract one from the stack depth and store this total length in
[1+z:tz0<T]dsTx is a macro that adds one to whatever is on the stack, and then pops that value, storing it at index(stack depth) in array
t. This basically means that if we started with the binary
t now holds
2, 1, 2, 2, assuming 1-indexing.
0dsj puts a zero on the stack so we don't get a stack empty error when we do our first addition, and it stores a zero in register
j as well.
[ljd1+dsj;tr3r^*+ljli>M]dsMx is, unfortunately, a lot of counter nonsense. We need register
j for two things - pull element
(j+1) from array
t, and multiply it by
3^j. We start macro
M by putting
j on the stack and duplicating it. We increment the new copy, duplicate it, and store it back into
j. With the copy of
(j+1) we left behind, we pull from array
t. Swap so that our original
j is at the top of the stack, do the necessary base-three math with
3r^*, add this 'bit' to our total, and then compare
i to see if we still have more 'bits' to do. At the very end, we