Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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 , the shortest answer in bytes will win.

Input will be anything from -32768 to 32767 (include sign byte handling in your code)

share|improve this question
    
Q: what does "sign byte handling" mean - shall I output "-xxxx" for a negative number? Then some of us are wrong, incl. me, as I output "11...11" for -1 (aka as unsigned) –  blabla999 Feb 16 at 2:19
    
Sign byte handling - the MSB of signed variables controls if they are negative –  TheDoctor Feb 16 at 3:12
    
sure, but do I have to >print< them as sign '-' followed by magnitude? –  blabla999 Feb 16 at 3:14
    
@blabla999 - No you don't –  TheDoctor Feb 16 at 3:34
    
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?.. –  mniip Feb 16 at 12:03

13 Answers 13

up vote 2 down vote accepted

GolfScript - 17 bytes

~{.1&\2/}16*;]-1%

Not too much more verbose than the built-in ~2base.

share|improve this answer
    
I don't know golfscript but a few sample runs lead me to conclude that you should remove the ~ –  ace Feb 16 at 22:10
    
@ace Because the initial input is a string "37", for example, the operation "37" & 1 (in infix) is a set-wise operation. The ~ at the front converts the input to an integer. –  primo Feb 17 at 2:38
    
I did my test here golfscript.apphb.com/… does this mean this interpreter is incorrect? (Sorry I really know nothing about golfscript) –  ace Feb 17 at 8:19
1  
The interpreter is correct; because you've pushed the integer value 10 onto the stack, it is not necessary to evaluate it. However, when read from stdin, the input will be a string (test here). The problem description also explicitly states that the input is a string. –  primo Feb 17 at 8:27

JavaScript, 46

for(x=prompt(o='');x;x>>>=1)o=(x&1)+o;alert(o)
share|improve this answer
    
Lol, I didn't even know that a 4-character operator (>>>=) existed! +1 (Also, if you run it in the console, you can save the last 9 characters.) –  Doorknob Feb 16 at 3:53
    
It's not 4-characters, it's two operators: the >>> is the 0-filling bitwise right shift, followed by an assignment. Try: x=8; x>>>=1; x; and x=8; x>>>1; x; -- in the first case, the value of x has changed; in the second, it has not. –  Graham Charles Feb 16 at 9:03
3  
@GrahamCharles >>>= is a single operator. –  primo Feb 16 at 13:43
    
Well, look at that! Thanks, @primo... you learn something every day! –  Graham Charles Feb 17 at 23:52
1  
@ComFreek That would reverse the order of the digits –  copy Feb 19 at 18:39

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.

share|improve this answer
1  
You can save the reverse by constructing the array backwards: @s=($x&1,@s). –  primo Feb 16 at 2:52
    
Now that the contest is over, the best I found was 34: $\=$_%2 .$\while$_=$_>>1||<>;print. Or, if command line options count one byte each, 27: 1while$\=$_%2 .$\,$_>>=1}{ using -p. –  primo Feb 20 at 14:22

Javascript 59

o='';i=parseInt(prompt());do{o=(i&1)+o}while(i>>=1)alert(o)
share|improve this 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)

share|improve this 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
share|improve this 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.

f(x){x<0?x*=-printf("-"):0;printf("%d",x%2,x&&f(x/2));}
share|improve this 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
share|improve this answer
1  
You can replace Math.floor with ~~, as the range for the numbers is small. –  Blender Feb 16 at 11:53
    
@Blender Thanks, I knew that there existed some way, just could not find it. –  Victor Feb 16 at 12:01
    
@Victor I don't know javascript so I might be wrong but at the end when you say a=x%2+a could this be shortened to a+=x%2 ? It works in all languages I know. –  Albert Renshaw Feb 16 at 23:10
    
@AlbertRenshaw No, This would be the same as a=a+x%2, but that + is for string concatenation. I.e, your suggestion results in the digits in the backwards order. –  Victor Feb 17 at 1:55
    
@Victor Ah! Thankyou! –  Albert Renshaw Feb 17 at 3:02

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?

share|improve this answer

Python - 61 60 characters

x=input();print"".join("01"[x>>i&1]for i in range(15,-1,-1))
share|improve this answer
2  
You can get rid of the space between print and "". –  Blender Feb 16 at 11:54
    
@Blender I was just about to suggest the same thing :) –  Albert Renshaw Feb 16 at 23:13
    
@Blender Ha true, didn't even notice. Done! –  C0deH4cker Feb 17 at 3:54

Python 3.x: 65 characters

b=lambda n:n<2 and'01'[n]or b(n//2)+b(n%2);print(b(int(input())))
share|improve this 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
share|improve this 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 upto 64 bits.

When executed the above method in Linqpad - rr = p(-32768); rr.Dump();

Output- 01111111111111111111111111111111111111111111111111000000000000000

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.