31
\$\begingroup\$

It seems we've managed to go all this time without a plain vanilla Number-To-Binary challenge! Whilst this will inevitably be only one element in many languages, it should put a few esolangs through their paces.

I truly looked for this challenge to no avail. If it already exists, comment as such and I'll delete this post-haste.

Input

A single non-negative integer.

Output

The same number as represented in Base 2.

Test Cases

  • 4 -> 100
  • 10 -> 1010
  • 1234 -> 10011010010

Victory Condition

, so fewest bytes wins!

Notes

\$\endgroup\$
8
  • 4
    \$\begingroup\$ Related, related. \$\endgroup\$
    – chunes
    Feb 27 at 3:27
  • 2
    \$\begingroup\$ @chunes Both are source restricted, which makes them different challenges \$\endgroup\$
    – ATaco
    Feb 27 at 3:36
  • 3
    \$\begingroup\$ Still it’s often helpful for golfers to know of related challenges. \$\endgroup\$
    – doug
    Feb 27 at 7:09
  • 3
    \$\begingroup\$ @KevinCruijssen Leading zeroes are fine, Trailing zeroes go without saying are not. \$\endgroup\$
    – ATaco
    Feb 27 at 8:26
  • 2
    \$\begingroup\$ Can we output the binary as little-endian? \$\endgroup\$
    – pajonk
    Mar 1 at 11:41

70 Answers 70

11
\$\begingroup\$

Piet + ascii-piet, 29 bytes (6×9=54 codels)

tkvuumf_iliqqdltT QqKln?_sf ?

Try Piet online!

B2C2 is I (no-op). The printing loop is now:

O d 1 % D I

which nicely forms a color loop.


Piet + ascii-piet, 33 bytes (5×9=45 codels)

tkvuumf_iliqqdltT _?tser?_iqtf? ?

Try Piet online!

The bit-extracting logic is the same as Parcly Taxel's. The printing logic is new.

Loop 1: push bits of the input (A1 -> A8 -> B8 -> B1 -> A1)

D           No-op
I           Take input (n); no-op afterwards
d 2 %       [...bits n n%2]
2 1 r 2 /   [...bits n%2 n/2]
d ! D       Turn right if the new n is 0

Now there is a leading zero, which is handled nicely by A2->B2 (>). Since the number below is 0 or 1, and 0>0 == 0 and 1>0 == 1, the net effect is to simply remove the extra zero.

Loop 2: print bits until the stack is empty (D2 -> E2 -> E1 -> D2 -> D5 -> E4 -> E1)

d 1 > !    If the top exists, push 1; otherwise push 0
D          Turn right if it is 1; halt otherwise (white trap)
O          Output as number
\$\endgroup\$
10
\$\begingroup\$

Piet + ascii-piet, 73 bytes (7×12=84 codels)

um    R metabrujjL    ?  ll?dD    j  d ?T    l rr tN   ttbj nfI        nn

Try Piet online!

\$\endgroup\$
2
  • \$\begingroup\$ There is output as number instead of output as character, so you can save the bytes used to make the constant 48 to make the char codes. \$\endgroup\$
    – Aiden Chow
    Feb 28 at 5:44
  • \$\begingroup\$ Also, generally speaking, making your code thinner will be better in minimizing the amount of black codels, thereby reducing the byte count as well. I'm not entirely sure how that could be achieved with your code (especially since Piet code is hard to parse lol), but a lot of bytes could potentially be saved by changing the structure around a bit to minimize black codels. \$\endgroup\$
    – Aiden Chow
    Feb 28 at 5:45
10
\$\begingroup\$

Piet + ascii-piet, 50 44 42 bytes (2×25=50 2×22=44 2×21=42 codels)

tabru?qd?t?itknmdjem_  a?liqdltailckt?iq ?

Try Piet online!

Pointer Path

\$\endgroup\$
9
\$\begingroup\$

Python, 13 bytes

"{:b}".format

Attempt This Online!

\$\endgroup\$
9
\$\begingroup\$

Brain-Flak, 132 bytes

{(({})<><(()())>)({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{})<>({}<(()())>)({}(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>)}<>

Outputs the individual numbers in a list with newlines as separators, and does not output anything for 0.

Explanation:

{                                                                   #  loop while top of left stack is not 0
(({})<><(()())>)({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{})<>    #  leave the result of modulo 2 on right stack
({}<(()())>)({}(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>)    #  integer division by 2 on left stack
}                                                                   #  end loop
<>                                                                  #  switch to right stack
                                                                    #  implicit output of active (right) stack

Try it online!

I'm not the best at this language so I may have left a lot of room for further golfing, please let me know if you found a better way to do it.

\$\endgroup\$
2
7
\$\begingroup\$

Thunno, \$ 1\log_{256}(96)\approx \$ 0.82 bytes

b

Attempt This Online!

\$\endgroup\$
1
  • 6
    \$\begingroup\$ I got confused by the log256(96), but now realize that that's an approximation of how many bytes each command takes in the Thunnu language, and this has 1 command. I get it now, it makes sense. \$\endgroup\$ Feb 27 at 17:48
7
\$\begingroup\$

Pure Bash (no external utilities), 37

b()(((a=$1/2))&&b $a
echo -n $[$1%2])

Try it online!

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. 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 ))
}
\$\endgroup\$
4
  • \$\begingroup\$ Gods above. Make it a one-liner: "b()(((a=$1/2))&&b $a; printf %d $[$1%2])" and paste at the bash prompt. Then the command "b 346363" yields the output "010100100011111011" ... I'd appreciate it if you'd edit the answer to explain how it works. \$\endgroup\$
    – Wastrel
    Feb 28 at 16:17
  • 1
    \$\begingroup\$ @Wastrel Explanation added. \$\endgroup\$ Mar 1 at 0:13
  • 1
    \$\begingroup\$ Thank you, and thanks for the more readable version. Bash lacks the built-in ability to do this operation, unlike many of the other languages given as an answer, and I enjoy seeing the problem deconstructed and solved. (In 37 characters!) Oops, "b 346363" yields the output "010100100011111011" is bad copy-paste, it should have been "1010100100011111011" \$\endgroup\$
    – Wastrel
    Mar 1 at 15:04
  • \$\begingroup\$ save 1 byte using printf instead of echo -n 😀 \$\endgroup\$
    – roblogic
    Jul 24 at 13:37
6
\$\begingroup\$

JavaScript, 16 bytes

x=>x.toString(2)

Try it online!

\$\endgroup\$
6
\$\begingroup\$

K (ngn/k), 2 bytes

2\

Try it online!

\$\endgroup\$
6
\$\begingroup\$

05AB1E, 1 byte

b

Try it online!

\$\endgroup\$
6
\$\begingroup\$

bc - 14 bytes

obase=2;read()

Run bc by typing bc into a terminal and pressing Enter. Type this code in, press Enter, type in the number to convert, and finally press Enter one more time. Press Ctrl + C to exit bc.

read() reads user input (in base 10 by default), and then obase=2 sets it to output in binary. Given that we don't tell it to do any math operations (other than base-conversion), it just outputs the input, but in binary due to the obase=2.

Example:

$ bc
bc 1.07.1
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
obase=2;read()    <-- Press Enter
1234              <-- Press Enter again
10011010010       <-- Press Ctrl + C to exit
^C
(interrupt) Exiting bc.

I've tested this on Arch Linux, but any system with bc installed should work.

\$\endgroup\$
2
  • \$\begingroup\$ Just as a note: You can also store that code into a file and pass the file name to bc (or bc -q to omit all the copyright + warranty output). On my Ubuntu, Ctrl-C just gives me "(interrupt) use quit to exit.", Ctrl-D actually exits. \$\endgroup\$ Mar 2 at 0:16
  • \$\begingroup\$ This also seems to work without the read()? \$\endgroup\$ Mar 2 at 0:20
6
\$\begingroup\$

C (GCC), 21 bytes

f(n){printf("%b",n);}

Attempt This Online!

Will be pretty shocked if there is any way to do it shorter in C (unless I missed a weird print function).

\$\endgroup\$
2
  • \$\begingroup\$ Save 5 bytes if you compile with -Dp="printf" and replace printf with p. [This is probably cheating :) ] \$\endgroup\$
    – Joseph
    Mar 8 at 5:07
  • 2
    \$\begingroup\$ @Joseph yes, but then I'll be golfing the language: C -Dp="printf", not C \$\endgroup\$
    – badatgolf
    Mar 8 at 8:49
6
\$\begingroup\$

Haskell, 31 bytes

f 0=0
f n=n`mod`2+10*f(n`div`2)

Try it online!

I'm unsure why f$n`div`2 doesn't work as opposed to f(n`div`2)... I hope someone can explain this to me and help golf this code.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 3+f$x+y is equivalent to (3+f) (x+y) which is why it doesn't work. \$\endgroup\$
    – naffetS
    Feb 28 at 21:59
6
\$\begingroup\$

Quipu, 78 bytes

2&1@0&2&0&3&
//**[][][][]
1&2&2&++1&/\
>>>>%%  --
\/1&1&  0&
    []  >>
    **

Attempt This Online!

Explanation

Programs in Quipu consist of several "threads," vertical strips of code that are executed one at a time and also store values. Quipu is missing a lot of features that would have been useful for this challenge: lists, string concatenation, exponentiation... Lacking better methods, we generate the output as a base-10 number whose digits are either 0 or 1.

The first time thread 0 is executed, it loads the input number; subsequently, it divides its value by 2:

    # Previous value of this thread (implicit; initially 0)
2&  # Push 2
//  # Divide
1&  # Push 1
>>  # Go to that thread if the above result is greater than 0
\/  # Otherwise, read input number

Thread 1 generates successive powers of 10, starting at 1:

    # Previous value of this thread
1@  # Push 10
**  # Multiply
2&  # Push 2
>>  # Go to that thread if the above result is greater than 0
1&  # Otherwise, push 1

Thread 2 takes the current value mod 2 and multiplies by the appropriate power of 10:

0&  # Push 0
[]  # Load that thread's value
2&  # Push 2
%%  # Mod
1&  # Push 1
[]  # Load that thread's value
**  # Multiply

Thread 3 keeps a running sum of the values generated by thread 2. This will be our output number.

    # Previous value of this thread
2&  # Push 2
[]  # Load that thread's value
++  # Add

Thread 4 tests if the value in thread 0 is still greater than 1; if so, jump back to thread 0:

0&  # Push 0
[]  # Load that thread's value
1&  # Push 1
--  # Subtract
0&  # Push 0
>>  # Go to that thread if the above result is greater than 0

Once thread 0's value has reached 1 (or 0), execution continues with thread 5, which simply outputs the final result:

3&  # Push 3
[]  # Load that thread's value
/\  # Print
\$\endgroup\$
5
\$\begingroup\$

Python, 17 bytes

lambda n:f"{n:b}"

Attempt This Online!

\$\endgroup\$
5
\$\begingroup\$

Vyxal, 1 byte

b

Try it Online!

\$\endgroup\$
5
\$\begingroup\$

Befunge-93 (PyFunge), 28 bytes

2&v
2/>:0`!#^_:2%\
 ._@#-2:<

Try it online!

Explanation:

2&v and > below: Push 2 (used as an "end of string" character of sorts), push user input (henceforth X), then go down and enter the main loop.

Main Loop

:0\`!: Check if X is greater than 0. Invert the answer. (Specifically: duplicate X, push 0, swap, greater than, invert)

#^_: If top of stack is 1 (i.e. X <= 0), go up to print loop, else continue right. (Bridge, (up), horizontal if)

:2%: Get X%2. (Duplicate X, push 2, modulo)

\: Store below X on stack. (Swap)

2/: Divide X by 2. Loop restarts with this as X. (push 2, integer divide)

Print Loop

<: Go left. (going right here would add a ! but it would not increase bytes as we have a spare whitespace on the left)

-2:: Check if top of stack = 2 (end of string). (RTL; duplicate, push 2, subtract)

_@#: Terminate program if top of stack = 0 (i.e. next item is 2). (RTL; bridge, (terminate), horizontal if)

.: Print top of stack as integer.

Note: I originally had a $ to pop the leading 0 above the ^ in the main loop, but as per comments, leading 0s are allowed. Changing the ^ to a v would be equivalent, unless I were to add back in the $ at the cost of 6 vs 10 bytes.

\$\endgroup\$
5
\$\begingroup\$

Prolog (SWI), 26 bytes

:-read(X),format("~2r",X).

Try it online!

With builtin.

Prolog (SWI), 42 36 35 bytes

-6 bytes thanks to @Steffan

-1 byte thanks to @false

N+X:-N<1,X=0;N//2+B,X is N/\1+10*B.

Try it online!

Without builtin.


Man, I haven't golfed in Prolog in a while; I forgot how wonky it is to code in it lol. Please tell me if there are any more golfs!

\$\endgroup\$
9
  • \$\begingroup\$ For the second one you can do N+X:-A is N//2,A+B,X is(N/\1)+10*B. \$\endgroup\$
    – naffetS
    Feb 28 at 21:04
  • \$\begingroup\$ Or even better, N+X:-N<1,X=0;N//2+B,X is(N/\1)+10*B. avoiding one of the iss and then combining the two things and using <1 to automatically evaluate when checking for zero \$\endgroup\$
    – naffetS
    Feb 28 at 21:05
  • \$\begingroup\$ @Steffan Da hell is N/\1?? \$\endgroup\$
    – Aiden Chow
    Mar 1 at 3:24
  • \$\begingroup\$ n&1 in most langauges, it's just bitwise and with 1 (taking the last bit) \$\endgroup\$
    – naffetS
    Mar 1 at 3:29
  • \$\begingroup\$ -1 by removing the round brackets: N+X:-N<1,X=0;N//2+B,X is N/\1+10*B. \$\endgroup\$
    – false
    Mar 9 at 19:14
4
\$\begingroup\$

Minecraft Data Pack via Lectern, 355 bytes

@function a:b
data modify storage  b set value []
scoreboard players set  i 2
function a:c
@function a:c
scoreboard players operation a i = i i
data modify storage  b prepend value 0
execute store result storage  b[0] int 1 run scoreboard players operation a i %=  i
scoreboard players operation i i /=  i
execute if score i i matches 1.. run function a:c

The function is a:b.

Takes input in the fake player i and the objective i (Which can be set using /scoreboard objectives add i dummy, /scoreboard players set i i <input number>).

Outputs a list via data storage : b (Which can be read by /data get storage : b).

I'm not sure this I/O format is valid, but this would be the standard way to do that if you were writing a library, although with the objective created by the data pack (and, of course, with more meaningful names).

\$\endgroup\$
3
\$\begingroup\$

Whitespace, 70 bytes

[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input_n][N
S S N
_Create_Label_BINARY_LOOP][S N
S _Duplicate_n][N
T   S S N
_If_0_Jump_to_Label_PRINT_LOOP][S N
S _Duplicate_n][S S S T S N
_Push_2][T  S T T   _Modulo][S N
T   _Swap_top_two][S S S T  S N
_Push_2][T  S T S _Integer_divide][N
S N
N
_Jump_to_Label_BINARY_LOOP][N
S S S N
_Create_Label_PRINT_LOOP][T N
S T _Print_as_integer][N
S N
S N
_Jump_to_Label_PRINT_LOOP]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Outputs with one additional leading 0. This can be removed at the cost of 8 additional bytes:
Try it online.

Explanation in pseudo-code:

Integer n = STDIN as integer
Start BINARY_LOOP:
  If n==0:
    Jump to PRINT_LOOP
  Push n modulo-2 to the stack
  n = n integer-divided by 2
  Go to the next iteration of BINARY_LOOP

PRINT_LOOP:
  Print current top of the stack as integer to STDOUT
  Go to the next iteration of PRINT_LOOP

Stops the program with an error when it tries to print while the stack is empty.

\$\endgroup\$
3
\$\begingroup\$

Python 2, 62 54 bytes

i,o=input(),""
while i:i,j=divmod(i,2);o=`j`+o
print o

Try it online!

Just as a way of doing it without any builtins.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ 49 bytes \$\endgroup\$ Feb 27 at 12:35
  • \$\begingroup\$ @97.100.97.109 I thought about that but then for some bizarre reason that I cant explain I went for divmod (probably because I have never found a use for it before :)). Feel free to post it as your own answer if you wish. \$\endgroup\$
    – ElPedro
    Feb 27 at 12:49
  • 3
    \$\begingroup\$ To the downvoter. Care to explain why this deserves a downvote? It provides the requested output, it is the shortest answer specifically for Python 2 and it isn't a copy of or based on any other answer. I'm keen to know what is wrong with it. \$\endgroup\$
    – ElPedro
    Feb 27 at 13:48
3
\$\begingroup\$

MATL, 1 byte

B

Try it at MATL Online

\$\endgroup\$
3
\$\begingroup\$

Julia 0.7, 3 bytes

bin

Try it online!

Julia 1.x, 9 bytes

bitstring

Attempt This Online!

Prints with leading zeroes.

\$\endgroup\$
3
\$\begingroup\$

J, 2 bytes

#:

Attempt This Online!

#: returns the binary expansion of a given number y as a boolean list.

\$\endgroup\$
3
\$\begingroup\$

Desmos, 50 bytes

f(n)=mod(floor(n/2^{[floor(log_2(n+0^n))...0]}),2)

Try It On Desmos!

Try It On Desmos! - Prettified

\$\endgroup\$
3
\$\begingroup\$

Haskell, 62 bytes

import Data.Sequence
d 0=Nothing
d n=Just$divMod n 2
unfoldl d

Attempt This Online!

A different approach than Aiden Chow's answer; this one uses unfoldl from Data.Sequence, which is elegant but unfortunately much less golfy.

Explanation

unfold is conceptually the opposite of fold. fold takes a function that combines two values into one and a sequence of values, and returns a single value; unfold takes a function that splits one value into two and a single value, and returns a sequence of values. Specifically, the type of unfoldl looks like this:

unfoldl :: (b -> Maybe (b, a)) -> b -> Seq a

It takes a function and a single value of type b and returns a sequence of values of type a. The function must take a value of type b and return either a tuple containing one b and one a or Nothing. unfoldl applies the function repeatedly to the initial value, taking the first element of the tuple as the new value and saving off the second tuple elements as the sequence. It stops when it gets Nothing instead of a tuple.

In our case, both types are Int. We want the first element of the tuple to be the input int-divided by 2, and the second element to be the input mod 2. Conveniently, Haskell has a divMod function that returns exactly the tuple we want. Thus, our binary converter is just

unfoldl d

where d is a function that stops when it hits 0:

d 0 = Nothing

and otherwise returns the result of divMod wrapped in a Maybe:

d n = Just (divMod n 2)
\$\endgroup\$
1
  • \$\begingroup\$ Another way to do it in 62 bytes \$\endgroup\$
    – Wheat Wizard
    Mar 1 at 0:02
3
\$\begingroup\$

Swift, 55 49 20 bytes

-6 bytes thanks to @RydwolfPrograms
-29 bytes thanks to @Jacob
{String($0,radix:2)}

Try it online!

\$\endgroup\$
5
  • \$\begingroup\$ Welcome to Code Golf! Does Swift let you remove some of the whitespace, like the space after the comma, or the newlines/indentation? \$\endgroup\$ Feb 27 at 22:26
  • \$\begingroup\$ @RydwolfPrograms it does, thank you for pointing that out! \$\endgroup\$
    – user117104
    Feb 27 at 22:30
  • \$\begingroup\$ I've never used Swift before but here's 20 bytes (just gathered from the tips post and recent golfed answers) \$\endgroup\$
    – noodle man
    Mar 1 at 2:20
  • \$\begingroup\$ @Jacob thank you! Is it OK if I update my answer with your solution, or is that against the rules? \$\endgroup\$
    – user117104
    Mar 1 at 2:34
  • \$\begingroup\$ @MrDeveloper Take it, gave it to you \$\endgroup\$
    – noodle man
    Mar 1 at 2:42
2
\$\begingroup\$

Java 8, 18 bytes

n->n.toString(n,2)

Try it online.

Explanation:

n->               // Method with Integer parameter and String return-type
  n.toString(n,2) //  Convert and return the given Integer as base-2 String
\$\endgroup\$
2
\$\begingroup\$

Retina 0.8.2, 23 bytes

.+
$*
+`(1+)\1
$+0
01
1

Try it online! Link includes test cases. Code is taken from the Retina 0.8.2 unary arithmetic tutorial for decimal to unary and unary to binary, except that for decimal to unary, the input is assumed to be decimal, so . is used instead of \d, and for unary to binary, ${1} is golfed to $+.

\$\endgroup\$
2
\$\begingroup\$

C# (.NET Core), 24 bytes

x=>Convert.ToString(x,2)

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to Code Golf! \$\endgroup\$ Feb 27 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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