26
\$\begingroup\$

This is a code golf challenge. Just like the title says, write a program to covert a string of ascii characters into binary.

For example:

"Hello World!" should turn into 1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100 100001.

Note: I am particularly interested in a pyth implementation.

\$\endgroup\$
9
  • 1
    \$\begingroup\$ We had the reversed asked: codegolf.stackexchange.com/questions/35096/… \$\endgroup\$
    – hmatt1
    Commented Jan 23, 2015 at 0:57
  • 1
    \$\begingroup\$ I noticed that. There's an anecdote for why I asked this question. I encouraged my friend to learn programming, and he took a java class last summer where each student had to pick a project. He told me he wanted to translate text to binary, which I then did (to his dismay) in python 3 in 1 line (a very long line). I find it incredible that his project idea can be distilled down to 8 bytes. \$\endgroup\$ Commented Jan 23, 2015 at 4:12
  • 2
    \$\begingroup\$ that's cool, thanks for sharing! I do like easier questions like this because it gives more people a chance to participate and generates lots of content in the form of answers. \$\endgroup\$
    – hmatt1
    Commented Jan 23, 2015 at 4:22
  • 1
    \$\begingroup\$ Does it has to be ASCII? i.e., if a technology is not ASCII compatible, could the results reflect that? \$\endgroup\$ Commented Apr 13, 2019 at 11:13
  • 6
    \$\begingroup\$ Is it acceptable to output with a separator other than spaces (e.g. a newline)? \$\endgroup\$ Commented Sep 3, 2019 at 9:51

65 Answers 65

1
\$\begingroup\$

Perl 5, 21 bytes

printf'%b ',ord for@F

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Gaia, 4 bytes

ċb¦ṡ

Pretty happy with this

How it works

ċ   Get a list of all the code points in the input string
b¦  Convert every number in that list to binary
ṡ   Joins the element of the list with spaces
Implicit Output 

Try it Online!

\$\endgroup\$
1
\$\begingroup\$

Shakti, 8 3 bytes

In 2020.02.19:

10/2\`c?

Example:

 10/2\`c?"Hello World!"
1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100 100001

Update: 3 bytes in 2020.02.23, via Arthur: 2\'

\$\endgroup\$
1
\$\begingroup\$

JavaScript (V8), 52 bytes

a=>[...a].map(p=>p.charCodeAt().toString(2)).join` `

Try it online!

Beats all existing JS answers.

\$\endgroup\$
1
\$\begingroup\$

brainfuck, 465 455 443 356 bytes

>>,[<+<+>>-]<[[-]>+++++++>+[>[-]>>[-]<<<<<<[>>>>+>+<<<<<-]>>>>[<<<<+>>>>-]<<[>>+>>+<<<<-]>>>>[<<<<+>>>>-]<<[>>[-]++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>>[-]>[<<<+>>>-]<<<<-]>>[-]++<[>->+<[>]>[<+>-]<<[<]>-]<<[-]>>>>[<<<+<+>>>>-]<<<<<<[>>>+<<<-]>>>[[-]>>[-]-[<+>-----]<---[<<+<<+>>>>-]<<.[-]>]<<[>+>+<<-]>>-[<<+>>-]<]++++[>++++++++<-]>.<<<<[-]>[-]>[-],[<+<+>>-]<]

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Zsh --extendedglob, 30 bytes

<<<${1//(#m)?/$[[##2]#MATCH] }

Try it online!

//Replace every (#m) matched ? single character with its binary representation. [#2] leaves a 2# prefix on, [##2] strips it.


Zsh, 43 36 bytes

for c (${(s::)1})printf $[[##2]#c]\ 

Try it online! Try it online! Try it online!

for c (${(s::)1})                           # for character in string $1   (e.g. H)
                       $[       ]          # arithmetic evaluation
                       $[     #c]          # get character code           (e.g. 72)
                       $[[##2]#c]          # convert to base 2            (e.g. 1001000)
               printf  $[       ]\    # append space, print

If all binary strings need to be 8 characters long, +5 bytes:

for c (${(s::)1})printf %08d\  $[[##2]#c]

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ using printf for 43 bytes \$\endgroup\$
    – roblogic
    Commented Sep 3, 2019 at 0:23
1
\$\begingroup\$

K (ngn/k), 12 6 bytes

{2\'x}

Try it online!

-6 bytes thanks to @coltim

Returns a 2D array.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I think this can be just 2\' \$\endgroup\$
    – coltim
    Commented May 15, 2022 at 17:48
0
\$\begingroup\$

STATA 158

I used a different approach than most. Read in via the display _request() prompt (shortened to di _r(r)). Write the string to a file called b in text mode. Open b in binary mode and read each character as a byte and convert to binary. Technically the b file should be closed at the end, but it is a valid program and runs successfully without it.

di _r(r)
file open a using "b",w
file w a "$r"
file close a
file open a using "b",b r
file r a %1bu t
while r(eof)==0 {
loc q=t
inbase 2 `q'
file r a %1bu t
}
\$\endgroup\$
0
\$\begingroup\$

Never will C# win these kinds of questions but here's a try, completely without encoding. :)

C# - 84

Console.Write(String.Join(" ",Console.ReadLine().Select(x=>Convert.ToString(x,2))));
\$\endgroup\$
2
  • \$\begingroup\$ This could be made much shorter by using a lambda function, ie: x=>String.Join(" ",x.Select(y=>Convert.ToString(y,2))); However note that, due to using .Select(), both this shorter answer, and your original answer, need to include the 18 bytes for using System.Linq; unless you specify that it's using the Visual C# Interactive Compiler, which imports System.Linq by default \$\endgroup\$
    – Mayube
    Commented Apr 15, 2019 at 15:09
  • \$\begingroup\$ Here's the lambda function solution using Interactive Compiler, total of 55 bytes \$\endgroup\$
    – Mayube
    Commented Apr 15, 2019 at 15:10
0
\$\begingroup\$

Cobra - 64

As a Lambda:

do(s='')=(for c as int in s get Convert.toString(c,2)).join(' ')
\$\endgroup\$
0
\$\begingroup\$

Postscript, 17 bytes (13 byte program + 4 character command line switch)

s { 2 7 string cvrs = } forall

Which is 31 bytes in tokenized form: (backticks denote literal characters, everything else is hexidecimal)

`s{2 7` 92A5 9230 `=}` 9249

Run using Ghostscript as:

gs -ss="Hello World!" string-to-binary.ps
\$\endgroup\$
0
\$\begingroup\$

JavaScript 78

alert(eval('""'+prompt().replace(/./g,"+' '+'$&'.charCodeAt().toString(2)")))
\$\endgroup\$
0
\$\begingroup\$

Ruby 38 Bytes

p gets.bytes.map{|i|i.to_s 2}.join ' '
\$\endgroup\$
1
  • \$\begingroup\$ .join ' ' can be shortened to *' '. \$\endgroup\$ Commented Jan 23, 2015 at 22:59
0
\$\begingroup\$

Erlang, 71 Bytes

f(S)->L=lists,L:droplast(L:flatten([integer_to_list(X,2)++" "||X<-S])).

If a trailing whitespace at the end is allowed then

55 Bytes

f(S)->lists:flatten([integer_to_list(X,2)++" "||X<-S]).
\$\endgroup\$
0
\$\begingroup\$

Julia, 23 bytes

f(n)=[bin(a)for a in n]
\$\endgroup\$
0
\$\begingroup\$

q/kdb+, 18 bytes

Solution:

" "sv"01"0b vs'4h$

Example:

q)" "sv"01"0b vs'4h$"Hello World!"
"01001000 01100101 01101100 01101100 01101111 00100000 01010111 01101111 01110010 01101100 01100100 00100001"

Explanation:

Convert string to byte array, convert each byte to binary, index into the string "01" and then join strings together with whitespace " ":

" "sv"01"0b vs'4h$ / the solution
               4h$ / cast ($) to type byte (4h)
         0b vs'    / convert each (') byte to binary (0b vs)
     "01"          / (implicit) index into "01" (false;true)
" "sv              / join (sv) with " "
\$\endgroup\$
0
\$\begingroup\$

Shell utils, 102 bytes

I'm kind of ashamed of this.

xxd -b|sed -r "s/^.*: //;s/  .+$//;s/0*([01]+)/\1/g"|tr \n\r " "|sed -r "s/ +/ /g;s/ *1101 *1010 *$//"

Since I'm (possibly) running utilities from various archives across the Internet on Windows, I'll list the version information for each:

xxd V1.10 27oct98 by Juergen Weigert
GNU sed version 4.2.1
tr (GNU textutils) 2.0
Microsoft Windows [Version 10.0.15063]
\$\endgroup\$
0
\$\begingroup\$

PHP, 59 bytes

<?foreach(str_split($argv[1])as$a)echo decbin(ord($a)).' ';

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Deorst, 8 bytes

vombkE]_

Try it online!

How it works

Example input: ab

vo       - Map ordinal;      STACK = [[97, 98]]
  mb     - Map binary;       STACK = [['1100001', '1100010']]
    k    - Turn off sort;    STACK = [['1100001', '1100010']]
     E]  - Flatten;          STACK = ['110001', '1100010']
       _ - Join with spaces; STACK = ['110001 1100010']
\$\endgroup\$
0
\$\begingroup\$

Java 8, 112 bytes

Takes input as a command line argument

interface M{static void main(String[]a){a[0].chars().forEach(i->System.out.print(Long.toBinaryString(i)+" "));}}

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ I'm so tired right now that I forgot I already did this challenge and almost posted a duplicate. \$\endgroup\$ Commented Apr 16, 2019 at 12:32
0
\$\begingroup\$

Perl 6, 16 bytes

*.ords>>.base(2)

Try it online!

Converts the string to codepoints and then each to base 2.

\$\endgroup\$
0
\$\begingroup\$

05AB1E, 10 bytes

SvyÇ2Bнð«?

S           //Split string
 v          //Loop on every character
  y         //Push current character to the stack
   Ç        //Get ASCII value of character
    2B      //Convert to base 2
      н     //Convert from 1-element array to string
       ð«   //Append space
         ?  //Print with no newline

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Python 3, 39 bytes

for i in input():print(bin(ord(i))[2:])

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to the site! While I'm sure it's a non-issue, the post asks for spaces, not newlines, between the binary chunks. I've commented on the question asking if newlines are acceptable for you. In addition, I've edited in a link to Try it online! so that others can verify that your solution works. \$\endgroup\$ Commented Sep 3, 2019 at 9:51
0
\$\begingroup\$

Japt -S, 4 bytes

¬®c¤

Try it

¬®c¤     :Implicit input input of string U
¬        :Split
 ®       :Map
  c      :  Character code
   ¤     :  To binary string
         :Implicitly join with spaces and output

Or, if we can take input as an array of characters ...

Japt -mS, 2 bytes

Try it

\$\endgroup\$
0
\$\begingroup\$

Erlang 41

[io:fwrite('~.2B ',[C])||C<-io:read("")].
\$\endgroup\$
2
  • \$\begingroup\$ How is this answer called? Is it a complete program? Is it a function? Is it something else? \$\endgroup\$
    – Wheat Wizard
    Commented Sep 3, 2019 at 18:35
  • \$\begingroup\$ Fixed to be full program. \$\endgroup\$
    – Hauleth
    Commented Sep 4, 2019 at 16:57
0
\$\begingroup\$

Elixir 47

for c<-:io.read(''),do: :io.fwrite('~.2B ',[c])

As function:

& for<<c<-&1>>,do: :io.fwrite('~.2B ',[c])

As function working on charlists (' delimited strings):

& for c<-&1,do: :io.fwrite('~.2B ',[c])
\$\endgroup\$
0
\$\begingroup\$

Burlesque, 10 bytes

XX{**b2}mw

Try it online!

XX  # Break into characters
{
 ** # Convert to ascii val
 b2 # Convert to binary
}mw # Map and spaces between elements 
\$\endgroup\$
0
\$\begingroup\$

PHP, 44 bytes

while($c=decbin(ord($argn[$i++])))echo"$c ";

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Pip -s, 6 bytes

TB*A*a

Converts to ASCII/Unicode, then to binary. the -s flag joins lists on space.

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Husk, 7 bytes

wm(ṁsḋc

Try it online!

\$\endgroup\$

Your Answer

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

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