Brainf*ck, 98 77
Obviously this isn't for the purpose of winning but what would a competition be if it didnt have a brainfk solution
++++[>++++<-]>>,<[->>++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]++++++[->++++++++<]>.[-]>[-<<<+>>>]<<<<]
Since brainfk can only handle 8bit integers and no negatives I guess it doesn't fully abide by the rules but hey I was never in it to win it.
This actually does work for 16-bit input if your interpreter supports
I even got it to output in ascii values
Here is the annotated code:
++[>++++<-] preload 8 onto cell 1
>>,< input into cell 2
[- iterate over cell 1
>>++< put 2 in cell 3
[->-[>+>>]>[+[-<+>]>+>>]<<<<<] division algorithm: converts {n d} into {0 d_minus_n%d n%d n/d}
>[-]++++++[->++++++++<]> clears cell 4 and puts 48(ascii of 0) into cell 5
.[-] output n%2 and clear it (the bit)
>[-<<<+>>>] bring n/2 into cell 2 (to be used for division in next iteration)
<<<<] end iterate
Shorter algorithm (77):
+>,>-<[>>[->]++[-<+]-<-]++++++++[->++++++<]>+[->+>+>+>+>+>+>+>+<<<<<<<<]>[.>]
This one can only handle 8bit integers.
The algorithm works by using a binary counter which is actually very short (one increment is >[->]++[-<+]-<-
which then lays out the bits. The issue is that it is difficult to print out all of the bits
That last algorithm can be adapted to fit any number of bits at the expense of bytes. To be able to deal with N bit integers, it requires 53+3*N bytes to encode.
examples:
(1 bit) +>,>-<[>>[->]++[-<+]-<-]++++++++[->++++++<]>+[->+<]>[.>]
(2 bit) +>,>-<[>>[->]++[-<+]-<-]++++++++[->++++++<]>+[->+>+<<]>[.>]
(3 bit) +>,>-<[>>[->]++[-<+]-<-]++++++++[->++++++<]>+[->+>+>+<<<]>[.>]
etc
the MSB of signed variables controls if they are negative
- that sounds like sign bit, however as the range-32768..32767
suggests, you want 2's complement. So which do you want?.. \$\endgroup\$