# Number to Binary

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

• The output must consist of digits 0 and 1, either as characters or individual numbers in a list.
• Zero may optionally return nothing.
• Standard IO Applies
• Standard Loopholes Apply
• Have Fun!
• Feb 27 at 3:27
• @chunes Both are source restricted, which makes them different challenges Feb 27 at 3:36
• Still it’s often helpful for golfers to know of related challenges.
– doug
Feb 27 at 7:09
• @KevinCruijssen Leading zeroes are fine, Trailing zeroes go without saying are not. Feb 27 at 8:26
• Can we output the binary as little-endian? Mar 1 at 11:41

# 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!

• 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. Feb 28 at 5:44
• 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. Feb 28 at 5:45

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

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


Try Piet online!

# Python, 13 bytes

"{:b}".format


Attempt This Online!

# 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.

• Nice! This is what I was hoping to see Feb 27 at 8:09

# JavaScript, 16 bytes

x=>x.toString(2)


Try it online!

# 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


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

b


Attempt This Online!

• 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. Feb 27 at 17:48

# K (ngn/k), 2 bytes

2\


Try it online!

## 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. • 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. Mar 2 at 0:16 • This also seems to work without the read()? Mar 2 at 0:20 # 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). • Save 5 bytes if you compile with -Dp="printf" and replace printf with p. [This is probably cheating :) ] Mar 8 at 5:07 • @Joseph yes, but then I'll be golfing the language: C -Dp="printf", not C Mar 8 at 8:49 # Haskell, 31 bytes f 0=0 f n=nmod2+10*f(ndiv2)  Try it online! I'm unsure why f$ndiv2 doesn't work as opposed to f(ndiv2)... I hope someone can explain this to me and help golf this code.

b $a fi echo -n$(( $1 % 2 )) }  • 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. Feb 28 at 16:17 • @Wastrel Explanation added. Mar 1 at 0:13 • 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" Mar 1 at 15:04 # Python, 17 bytes lambda n:f"{n:b}"  Attempt This Online! # Vyxal, 1 byte b  Try it Online! # 05AB1E, 1 byte b  Try it online! # 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. # Prolog (SWI), 26 bytes :-read(X),format("~2r",X).  Try it online! With builtin. # Prolog (SWI), 4236 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! • For the second one you can do N+X:-A is N//2,A+B,X is(N/\1)+10*B. Feb 28 at 21:04 • 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 Feb 28 at 21:05 • @Steffan Da hell is N/\1?? Mar 1 at 3:24 • n&1 in most langauges, it's just bitwise and with 1 (taking the last bit) Mar 1 at 3:29 • -1 by removing the round brackets: N+X:-N<1,X=0;N//2+B,X is N/\1+10*B. Mar 9 at 19:14 # 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. # 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. • 49 bytes Feb 27 at 12:35 • @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. Feb 27 at 12:49 • 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. Feb 27 at 13:48 # MATL, 1 byte B  Try it at MATL Online # Julia 0.7, 3 bytes bin  Try it online! # Julia 1.x, 9 bytes bitstring  Attempt This Online! Prints with leading zeroes. # J, 2 bytes #:  Attempt This Online! #: returns the binary expansion of a given number y as a boolean list. # 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 # 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)

• Another way to do it in 62 bytes Mar 1 at 0:02

{String($0,radix:2)}  Try it online! • Welcome to Code Golf! Does Swift let you remove some of the whitespace, like the space after the comma, or the newlines/indentation? Feb 27 at 22:26 • @RydwolfPrograms it does, thank you for pointing that out! Feb 27 at 22:30 • I've never used Swift before but here's 20 bytes (just gathered from the tips post and recent golfed answers) Mar 1 at 2:20 • @Jacob thank you! Is it OK if I update my answer with your solution, or is that against the rules? Mar 1 at 2:34 • @MrDeveloper Take it, gave it to you Mar 1 at 2:42 # 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). # Scratch, 70 68 bytes Puts a list of binary digits onto the a global variable, which is automatically displayed when the program finishes execution. Saved 2 bytes by using ([floor v]of((n)/(2 instead of ((n)-(((n)mod(2))/(2 Scratchblocks syntax: define a(n if<(n)>(0)>then a([floor v]of((n)/(2 add((n)mod(2))to[a v  Try it on Scratch # 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  # 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 \$+.