# 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!
• Commented Feb 27, 2023 at 3:27
• @chunes Both are source restricted, which makes them different challenges Commented Feb 27, 2023 at 3:36
• Still it’s often helpful for golfers to know of related challenges.
– doug
Commented Feb 27, 2023 at 7:09
• @KevinCruijssen Leading zeroes are fine, Trailing zeroes go without saying are not. Commented Feb 27, 2023 at 8:26
• Can we output the binary as little-endian? Commented Mar 1, 2023 at 11:41

# 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


# Python, 13 bytes

"{:b}".format


Attempt This Online!

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

# 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. Commented Feb 28, 2023 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. Commented Feb 28, 2023 at 5:45

# 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 Commented Feb 27, 2023 at 8:09
• Since you asked, here's the task in 40 bytes Commented Apr 2, 2023 at 4:05

# 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 ))
}

• 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. Commented Feb 28, 2023 at 16:17
• @Wastrel Explanation added. Commented Mar 1, 2023 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" Commented Mar 1, 2023 at 15:04
• save 1 byte using printf instead of echo -n 😀 Commented Jul 24, 2023 at 13:37

# 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. Commented Feb 27, 2023 at 17:48

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

• 3+f$x+y is equivalent to (3+f) (x+y) which is why it doesn't work. Commented Feb 28, 2023 at 21:59 # 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  # 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. Commented Feb 28, 2023 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 Commented Feb 28, 2023 at 21:05 • @Steffan Da hell is N/\1?? Commented Mar 1, 2023 at 3:24 • n&1 in most langauges, it's just bitwise and with 1 (taking the last bit) Commented Mar 1, 2023 at 3:29 • -1 by removing the round brackets: N+X:-N<1,X=0;N//2+B,X is N/\1+10*B. Commented Mar 9, 2023 at 19:14 # 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). # Python, 17 bytes lambda n:f"{n:b}"  Attempt This Online! # Vyxal, 1 byte b  Try it Online! # 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 Commented Feb 27, 2023 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. Commented Feb 27, 2023 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. Commented Feb 27, 2023 at 13:48 • It may have been auto-downvoted by the Community bot, it tends to do that to really short posts unfortunately Commented Feb 6 at 21:07 # Brain-Flak, 40 bytes {(<>)<>({<({}[()])><>[(()[{}])]()<>})}<>  Try it online! The other Brain-flak answer looked very long. # Explanation The first thing we can notice is that the following snippet: (()[{}])  does something very nice. It's equivalent to 1-x, which when constrained to the inputs of 0 and 1 will give us an increment and mod 2 operation. So we can calculate the mod 2 of a number by just repeating this snippet that many times starting with 0. {({}[()])<>(()[{}])<>}  This is nice and it can be modified to give us the full divmod. Each cycle we add the value of the accumulator we are building. Since it is 1 half the time and 0 the other half this gives us half the value. The one issue is it rounds up instead of down, so instead of adding n each step we add 1-n. That is we add 1 when the accumulator is 0 and 0 when the accumulator is 1. ({<({}[()])><>[(()[{}])]()<>})  Now we add a bit of code to add a new accumulator each step and we can just repeat this divmod process until the div is zero. {(<>)<>({<({}[()])><>[(()[{}])]()<>})}<>  # 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. # 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 Commented Mar 1, 2023 at 0:02

# Swift, 5549 20 bytes

##### -29 bytes thanks to @Jacob
{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? Commented Feb 27, 2023 at 22:26
• @RydwolfPrograms it does, thank you for pointing that out!
– user117104
Commented Feb 27, 2023 at 22:30
• I've never used Swift before but here's 20 bytes (just gathered from the tips post and recent golfed answers) Commented Mar 1, 2023 at 2:20
• @Jacob thank you! Is it OK if I update my answer with your solution, or is that against the rules?
– user117104
Commented Mar 1, 2023 at 2:34
• @MrDeveloper Take it, gave it to you Commented Mar 1, 2023 at 2:42

# R, 9 bytes

intToBits


Attempt This Online!

Outputs as little-endian with trailing zeros.

# R, 18 bytes

\(n)n%/%2^(n:0)%%2


Attempt This Online!

Outputs as big-endian (standard convention) with possibly a lot of leading zeros.

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