Trading States for Symbols with a Turing Machine
Here is one idea. Let $|w| = n$. We will have a tape symbol for each number in $\{0,1,\ldots,n\}$, which we will denote by $\langle i \rangle$. The machine starts by writing $\langle n \rangle$ on the tape. Then it repeatedly performs the following steps:


Read $\langle i \rangle$.
Depending on the value of $i$ and on $w$, switch to a write-0 or a write-1 state.
In write-$b$ step, move right until reaching the first blank, write $b$, then move left until reaching a cell of the form $\langle j \rangle$.
Replace $\langle j \rangle$ with $\langle j-1 \rangle$, or terminate if $j = 0$.


The exact implementation of this algorithm depends on your exact model. In your model, you might be able to do it using 5 states. But in any reasonable model, $O(1)$ states are needed, regardless of $w$.