[Question]
  [
**Background**:
> 
> You have been given an assignment to convert base 10 numbers to base 2 without using any premade base conversion functions. You can't use any imported libraries either.
> 
> 
> 
**Problem**:
Convert an input string from base 10 (decimal) to base 2 (binary). You may not use any premade base conversion code/functions/methods, or imported libraries. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes will win.
Input will be anything from -32768 to 32767 (include sign byte handling in your code)
  
[Answer]
# JavaScript, 46
```
for(x=prompt(o='');x;x>>>=1)o=(x&1)+o;alert(o)
```
[Answer]
# 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
```
[Answer]
## GolfScript - 17 bytes
```
~{.1&\2/}16*;]-1%
```
Not too much more verbose than the built-in `~2base`.
[Answer]
## Mandatory APL answer - 21 ~~22~~
```
"01"[1+2|⌊⎕÷2⋆⊖0,⍳15]
```
Examples:
```
      "01"[1+2|⌊⎕÷2⋆⊖0,⍳15]
⎕: 0
0000000000000000
      "01"[1+2|⌊⎕÷2⋆⊖0,⍳15]
⎕: 13
0000000000001101
      "01"[1+2|⌊⎕÷2⋆⊖0,⍳15]
⎕: 9999
0010011100001111
      "01"[1+2|⌊⎕÷2⋆⊖0,⍳15]
⎕: -3
1111111111111101
      "01"[1+2|⌊⎕÷2⋆⊖0,⍳15]
⎕: 32767
0111111111111111
```
[Answer]
# Turing Machine Code, 272 bytes
As usual, I'm using the rule table syntax defined [here.](http://morphett.info/turing/turing.html) You can test it on that site or, alternatively, using [this java implementation.](https://github.com/SuperJedi224/Turing-Machine)
A lot of the code is copied from my decimal-to-hex converter [here.](https://codegolf.stackexchange.com/a/68250/39022)
```
0 * * l B
B * * l C
C * 0 r D
D * * r E
E * * r A
A _ * l 1
A * * r *
1 0 9 l 1
1 1 0 l 2
1 2 1 l 2
1 3 2 l 2
1 4 3 l 2
1 5 4 l 2
1 6 5 l 2
1 7 6 l 2
1 8 7 l 2
1 9 8 l 2
1 _ * r Y
Y * * * X
X * _ r X
X _ _ * halt
2 * * l 2
2 _ _ l 3
3 * 1 r 4
3 1 0 l 3
4 * * r 4
4 _ _ r A
```
Counts down from the input in base 10 while counting up from 0 in base 2. On decrementing zero, it erases the input block and terminates.
[Answer]
# [Dyalog APL](http://dyalog.com/download-zone.htm), 11 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
2|⌊⎕÷2*⌽⍳16
```
`2|` The division remainder when halved of  
`⌊` the rounded down value of  
`⎕` the input  
`÷` divided by each of  
`2*` two to the power of each of  
`⍳16` {0, 1, 2, ..., 15}
Requires `⎕IO←0` which is default on many systems.
[TryAPL online!](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20%27Input%3A%20%20%27%2C%u2206%u2190%28%3F2*16%29-2*15%20%u22C4%20%27Output%3A%20%27%2C2%7C%u230A%u2206%F72*%u2296%u237316&run)
[Answer]
## Javascript 59
```
o='';i=parseInt(prompt());do{o=(i&1)+o}while(i>>=1)alert(o)
```
[Answer]
## Perl, 44
This is my first Perl program ever, so please forgive me if this can be easily golfed down further. Edit: Thank you @primo for taking 7 chars away from my answer.
```
$x=<>;do{@s=($x&1,@s)}while($x>>=1);print@s
```
```
$x=<>;do{push@s,$x&1}while($x>>=1);print reverse@s
```
The logic is essentially the same as my previous C solution.
Also, uses 64 bits.
[Answer]
# Javascript - ~~56~~ 48 and ~~36~~ 28 characters
* Does not works with negative numbers.
Thanks to @Blender for shaving 8 characters.
This form takes input and shows output, 48 characters:
```
x=prompt();for(a="";x;x=~~(x/2))a=x%2+a;alert(a)
```
If just an instruction that puts in a variable `a` the binary form of a variable `x` is needed (and you don't bother in destroying the `x` value as a side-effect), here it is with 28 characters:
```
for(a="";x;x=~~(x/2))a=x%2+a
```
[Answer]
# Python - ~~61~~ 60 characters
```
x=input();print"".join("01"[x>>i&1]for i in range(15,-1,-1))
```
[Answer]
## C, 55 chars
Prints an extra leading zero (for the sake of 2 bytes).  
Recursion within `printf` reverses the print order, so the algorithm extracts bits right-to-left but prints left-to-right. 
*EDIT*: Saved a char by using `putchar` instead of `printf`.
```
f(x){(x*=x<0?-printf("-"):1)&&f(x/2);putchar(48+x%2);}
```
[Answer]
# Excel, ~~91 90 81~~ 74
Trailing parens already discounted.
Compatibility note: `CONCAT()` was available only after later versions of 2016. It replaced `CONCATENATE()`. Tested in Excel online.
## Formulae
* `A1` - Input
* `B1` - `=A1+4^8*(A1<0)` (13) - Convert to 16-bit unsigned equivalent.
* `B2` - `=1+INT(LOG(B1,2))` (15) - Number of binary digits + 1
## Code (46):
Convert `B1` to binary.
```
=IF(A1=0,0,CONCAT(--ISODD(B1/2^(B2-SEQUENCE(B2)))))
```
Works in the full 16-bit range.
[Answer]
## C, 81
```
char b[17];i=15;main(x){scanf("%d",&x);while(i+1)b[i--]=(x&1)+48,x>>=1;puts(b);}
```
The output has strictly 16 bits (including padding zeros)
[Answer]
# Bash, 44
```
f=b+=n/2**e%2*10**e,2**e++/n?f=b:f;echo $[f]
```
Pass an input value to the script through the environment variable `n`. The decimal representation of the binary result cannot exceed `LONG_MAX`.
This should also be compatible with `ksh93` and `zsh` if `b` and `e` are initialized to `0` and proper arithmetic expansion is used.
[Answer]
# Apps Script + Google Sheets, ~~147~~ ~~144~~ 121 bytes
### Script
```
function j(decNumb){var str='';do{str=String(decNumb%2)+str;decNumb=decNumb/2|0;}while(decNumb>=1);return parseInt(str);}
```
### Sheet
```
=j(b1)
```
Modified version of [this script](https://stackoverflow.com/a/30966383) by ZygD.
[Answer]
# Haskell, 66 bytes
```
c 0=0
c n=c(div n 2)*10+mod n 2
b('-':r)='-':b r
b r=show.c.read$r
```
Call with `b "-1023"`, add `main=interact b` for a complete program or
[try it on Ideon.](http://ideone.com/JXYWnk)
`c` performs the conversion for positive integers.  
`b r=show.c.read$r` converts a string to a number, applies `c` and converts back to string.  
`b('-':r)='-':b r` strips a possible leading `-` and re-appends it to the result.
[Answer]
# PowerShell, ~~59~~ ~~87~~ ~~82~~ 70 bytes
+28 bytes for supporting negative numbers.  
-12 bytes thanks to @ASCII-only
```
param($d)$m=$d-lt0;while($d){$n="01"[$d%2]+$n;$d=($d-$d%2)/2}'-'*$m+$n
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVFUyXXViVFN6fEwLo8IzMnFSRUrZJnq2RgqBStkqJqFKutkmetkmILlNAF8TX1jWrVddW1VHKBEv///9c1NAAA "PowerShell – Try It Online")
Adapted from [this code](https://ss64.com/ps/syntax-base36.html). Takes input through a commandline parameter `-d`.
[Answer]
# APL(NARS), 17 chars, 34 bytes
```
{2∣⌊⍵÷2*(⍺-1)..0}
```
It is a copy and modify of Adam answer <https://codegolf.stackexchange.com/a/90107>
in the way one can add the parameter for the bits lenght,
and ⎕IO for this function (here is ⎕IO=1) should have no importance...
```
  f←{2∣⌊⍵÷2*(⍺-1)..0}
  16 f 2
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 
  32 f 2
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 
  32 f ¯1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 
  16 f ¯1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 
  64 f ¯12345678
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 0 0 1 1 1 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0 
```
it seeme easy handle the number of bits in this way (I cheked that last result should be right)
[Answer]
# Smalltalk (Smalltalk/X), 63/78
the first version creates an intermediate string (78):
```
t:=Number readFrom:Stdin.
((15to:1by:-1)collect:[:i|$0+(t>>i&1)]as:String)print
```
actually, there is no need to create the string; just output the chars (63):
```
t:=Number readFrom:Stdin.
15to:1by:-1 do:[:i|($0+(t>>i&1))print]
```
mhmh - is there a shorter way to read to a number?
[Answer]
# Python 3.x: 65 characters
```
b=lambda n:n<2 and'01'[n]or b(n//2)+b(n%2);print(b(int(input())))
```
[Answer]
# C# - 104
```
string p(int d){var r="";long i=1;while(r.Length<=64){var g=d&i;r=(g!=0)? "1"+r:"0"+r;i=i<<1;}return r;}
```
This method will convert decimal to binary up to `64` bits.
When executed the above method in Linqpad - 
 rr = p(-32768);
 rr.Dump();
Output: `01111111111111111111111111111111111111111111111111000000000000000`
[Answer]
# [Kotlin](https://kotlinlang.org), 82 bytes
```
{s:String->{var i=s.toInt()
var r=""
(0..15).map{r="${i and 1}$r"
i=i shr 1}
r}()}
```
[Try it online!](https://tio.run/##hVVfj9M4EH/3pxiilUhQm2z3BBzVFQkQD0grgcS@3KOTTBMLx87Zzi6l6mdfZuw0u8txuqpKrRnPzO@PnX6zQStzX72ADw5lwBb21kHolYfGtgid1Xtoeqk1mg63og9h9Nuq4iTnSh9k8w2/0xbKl40dqn8m9EFZ46uryzdvXooP1tyiC7B3doBaeoTNJQSblldwp0JvpwD1pHRYK5PiTSzy3EaI9zSic3Yy7VYIoM/fdoJe3iLUiAY6dUtPSV/vVWcGNIH7N/Pc80gzDTW1/M3oySvTUYMDjA4HSbR/wQD7yTSRUxlnN9I85zKMRWoYrWPptKqddAo9IHVGVwrxxdla40C4zzIQTmVGmuqD47FPZMlbbNQgdfEIZV4rI92hSKMHeQBjH4b/F2I2qFpgVwMS1davgNz9N94SvirTYPJ9tn7N9q4ohOB73u8Zu79DakAmHShAAmpND0NEP0VOMVBHZNTrzG79x9XrV38yJV68hpyG6YlAs12xFblpWs0F1PtgJxchFOJFJURVwcfvI@UJ8eIH0VhOZSmIJwlhG/Q@T7Ju4Wv8LWAHRz401OXsQKSUxCdI0Y@AHboVLVRQUqsfmCp4p0M/6bCa7wW59ApqFUhJ5suBZnKOjlyqoBTIFK@xU8bwFLt/PJOYkKJqHx5mzACgtXd0irlJSclb6ZbMbq4ug/1kQl7M6QSOsllGkfyyLDcvi3KQI5Hmi/KQvzieW/H8zekipbK47WHKeeV7BxvKnRgi9RPnXuKUFxyb5Y723PDZaB1dQ/c7ZwapTC5d57fwzjl5@CtZ87ZYnLmWQ93K5Zb92oS5ahhhd3/021S8fnuM8uz8okjUY0dCPJLhSAFivnDOhNqpRO4kHFE53UcAN@5A/GQbz8QjQ7huZgrJlEA7k7aMKd6KXSy9Vgbz4tmzmBsJY9Amzy7iDrpSF8cx53VxyoqZ9WcD9OLEkSmvoBmHUZNST2a2uJckui@jFY0MTQ85OmfdFm56Z@8kvV2KGdAy9L1s0ztmNb/aljZZ8QS6J@ySLfm8z7N0S7MVZPGW8mK94eflXMWu5ImPSeUp/r9052NE0on5PNFfzk8 "Kotlin – Try It Online")
[Answer]
# [Small Basic](http://www.smallbasic.com "Microsoft Small Basic"), 133 bytes
A script that inputs from and outputs to the `TextWindow` console.
```
n=TextWindow.Read()
While n>0
c=c+1
x[c]=Math.Remainder(n,2)
n=Math.Floor(n/2)
EndWhile
For i=0To c-1
TextWindow.Write(x[c-i])
EndFor
```
[Try it at SmallBasic.com](http://smallbasic.com/program/?DCZ401 "SmallBasic.com") *Requires Silverlight and thus must be run in IE.*
I/O is taken/given from the black console.
-22 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~50~~ 43 bytes
-7 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
```
f(n){printf("-%d"+(~n?n&&f(n/2),1:0),n&1);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zuqAoM68kTUNJVzVFSVujLs8@T00NKKFvpKljaGWgqZOnZqhpXfsfqEghNzEzT0OTq5qLM01D11TTWqGgtKRYQ0lJ0xokYm6BLmKAIlD7HwA "C (gcc) – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 43 bytes
```
param($n)15..0|%{$r+='01'[($n-shr$_)%2]}
$r
```
[Try it online!](https://tio.run/##dZDRCoJAFETf9ysucW1dUtk1ygiE/iNCpDZ8MLPVKFC/3a5mYkHDPs2ZGbibXx/aFIlO0xbPEELV5rGJLzZmQq08T9ZWhWYRcqn4nky3SAxGwvIPDUPTNoztbAYkxwbpAHD5Iy4G7CriXE0k6Y0YejxtEp@0l36w3nQD//ahSwTdhvoWJQTUYEHVJzFzUD9zfSz1ie7F6O0aXdzTkow5fQNmvTlDe/BdfRtLYvtJz1jTvgA "PowerShell – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~34~~ 33 bytes
```
|!/?=0:,2-}:%2:+***"  @"(0:
n{\~{
```
[Try it online!](https://tio.run/##S8sszvj/v0ZR397WwErHSLfWStXISltLS0tJQcFBScPAiiuvOqau@v///7plCrqGBgA "><> – Try It Online")
[Answer]
# [///](https://esolangs.org/wiki////), 124 bytes
```
/~/\/\///9/8*~8/7*~7/6*~6/5*~5/4*~4/3*~3/2*~2/1*~1/0*~*0/9*~0~/*/>Oⅼ~ⅼ>/ⅼ~ⅼO/Oⅼ~Oⅼⅼ/ⅼ\O~Oⅼ/_ⅼ~_~/>O/>~>~
```
[Try it online!](https://tio.run/##LYu7DcMwEEP3YfMk@d9oBS9gwHARIEU69eyyVabJIopkBOQRvAewvK7yfJRaMUcTbKzyyiIvzPLMJE@M8sggDyQ5EeVIkBXY5GBE3r/vj9tl/mXnRj2aOz32@@Ps/HTbkJ1dYxrqDw "/// – Try It Online")
Could be considered cheating, Outputs `ⅼ` and `O` instead of `1` and `0`, due to the mechanics of `///`.
Uses examples from the [wiki](https://esolangs.org/wiki////).
[Answer]
# [Perl 5](https://www.perl.org/), 26 bytes
Produces an additional leading `0` which can be avoided with two additional bytes (appending `}{`)
```
$\=($_&1).$\;redo if$_>>=1
```
[Try it online!](https://tio.run/##K0gtyjH9/18lxlZDJV7NUFNPJca6KDUlXyEzTSXezs7W8P9/w3/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online")
[Answer]
# Clojure 129 bytes#
Golfed version:
```
(defn p[n](loop[m 32768](if(> m 0)(do(if(= 0(bit-and m n))(print"0")(print"1"))(recur(unsigned-bit-shift-right m 1)))(println))))
```
Ungolfed:
```
(defn print-as-binary [n]
  (loop [mask  32768]
    (if (> mask 0)
      (do
        (if (= 0 (bit-and mask n))
          (print "0")
          (print "1"))
        (recur (unsigned-bit-shift-right mask 1)))
      (println))))
```
[Answer]
# PostgreSQL, 184 bytes
```
WITH RECURSIVE t(a,b,c)AS(SELECT abs($1),0,0 UNION ALL SELECT a/2,a%2,1from t where a>0)select case when $1<0then '-'else ''end||string_agg(b::text,''order by a)from t where c>0OR $1=0
```
137 bytes if only handling positive numbers
```
WITH RECURSIVE t(a,b,c)AS(SELECT $1,0,0 UNION ALL SELECT a/2,a%2,1from t where a>0)select string_agg(b::text,''order by a)from t where c>0
```
Input is given as an integer query parameter (using the extended query protocol or by wrapping in a function) and output is given as a string.
]