Pure Bash (no external utilities), 37
b()(((a=$1/2))&&b $a
echo -n $[$1%2])
This is a recursive function b()
that takes its argument and divides by 2. If the result is non-zero, then b()
is recursively called with the result. After the recursive call, the remainder when the argument is divided by 2 is the current binary digit. Ungolfed This is a pretty standard base conversion by repeated division by 2, with remainders becoming digits in base 2. Making it a recursive function has a couple of advantages here:
- Recursive function boilerplate is marginally shorter than while loop boilerplate for the same algorithm
- The repeated division yields digits (remainders) in reverse order to how they should be presented. By outputting the digit at each level after the recursive call, we effectively use the call stack to store the yielded digits and replay them back in the correct order
Ungolfed and perhaps a bit more readable:
function b() {
a=$(( $1 / 2 ))
if (( $a != 0 )); then
b $a
fi
echo -n $(( $1 % 2 ))
}