Sign up ×
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.

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.

share|improve this question
1  
We had the reversed asked: codegolf.stackexchange.com/questions/35096/… –  chilemagic Jan 23 at 0:57
    
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. –  ericmark26 Jan 23 at 4:12
1  
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. –  chilemagic Jan 23 at 4:22
    
Can I take input via a file (as specified at meta.codegolf.stackexchange.com/a/2452/30076)? –  bmarks Jan 23 at 16:08
    
I would prefer that you take a string as input, but if you feel that you can provide an interesting and/or unique solution by using a file for input, please feel free to do so. –  ericmark26 Jan 27 at 18:05

22 Answers 22

up vote 11 down vote accepted

CJam, 8 bytes

l:i2fbS*

Easy-peasy:

l:i           "Read the input line and convert each character to its ASCII value";
   2fb        "Put 2 on stack and use that to convert each ASCII value to base 2";
      S*      "Join the binary numbers by space";

Try it here

share|improve this answer

Scala - 59 - 55 Bytes

readLine().map(x=>print(x.toByte.toInt.toBinaryString))

Normally, one should use foreach and not map.

share|improve this answer

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

Ruby, 34 28 24 bytes

$<.bytes{|c|$><<"%b "%c}

Takes input via STDIN. 6 bytes saved thanks for AShelly and another 4 thanks to britishtea.

share|improve this answer
    
trim by 6 with $<.each_byte{|c|$><<"%b "%c} –  AShelly Jan 23 at 19:07
    
@AShelly nifty, thanks! –  Martin Büttner Jan 23 at 19:12
    
You can shave off some more characters by using String#bytes instead of String#each_byte. The block form is deprecated, but it still works :) –  britishtea Jan 23 at 22:16
    
@britishtea Oh, nice. thank you! –  Martin Büttner Jan 23 at 22:55

Python 3 - 43 bytes


print(*map("{:b}".format,input().encode()))

No quite the shortest, but an interesting approach IMO. It has the added advantage that if the number of significant bits varies, E.G. Hi!, padding with zeros is trivial (2 more bytes, as opposed to 9 for .zfill(8)):

print(*map("{:08b}".format,input().encode()))
share|improve this answer

JavaScript ES6, 63 65 bytes

alert([for(c of prompt())c.charCodeAt().toString(2)].join(' '))

This is rather long, thanks to JavaScript's long function names. The Stack Snippet below is the rough ES5 equivalent, so it can be run in any browser. Thanks to edc65 for the golfing improvements.

alert(prompt().split('').map(function(e){return e.charCodeAt().toString(2)}).join(' '))

share|improve this answer
1  
[for of] is slightly shorter than [...].map to enumerate charactes in strings: alert([for(c of prompt())c.charCodeAt().toString(2)].join(' ')) –  edc65 Jan 23 at 14:03

Ruby 38 Bytes

p gets.bytes.map{|i|i.to_s 2}.join ' '
share|improve this answer
    
.join ' ' can be shortened to *' '. –  Martin Büttner Jan 23 at 22:59

JavaScript 78

alert(eval('""'+prompt().replace(/./g,"+' '+'$&'.charCodeAt().toString(2)")))
share|improve this answer

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

Java - 148 Bytes

public class sToB{public static void main(String[] a){for(int i=0;i<a[0].length();i++){System.out.print(Integer.toString(a[0].charAt(i) ,2)+" ");}}}

Edited to include full file

share|improve this answer
2  
I think OP wants a full program, not just a snippet. Plus, it can be golfed a lot more, methinks. –  Rodolfo Dias Jan 23 at 11:47
    
that is the full program, if you put that in a main class, it will run. as for better golfing, probably but i could not spot how. –  Bryan Devaney Jan 23 at 13:10
1  
The full program includes the main class, too. –  Rodolfo Dias Jan 23 at 13:19
    
could be shorter using for(char c:a[0].toCharArray()){ or even for(byte b:a[0].getBytes()){ since the input is ascii, assuming a non-utf-16 machine locale –  njzk2 Jan 23 at 15:00
    
nice, I would never have thought of that. thank you. –  Bryan Devaney Jan 23 at 15:23

C++ - 119 bytes

Freeing memory? What's that?

#include<cstdio>
#include<cstdlib>
int main(int c,char**v){for(*v=new char[9];c=*(v[1]++);printf("%s ",itoa(c,*v,2)));}

(MSVC compiles the code with warning)

share|improve this answer
1  
C version, shorter main(int c,char**v){char x[9];for(;c=*(v[1]++);printf("%s ",itoa(c,x,2)));} –  n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Jan 23 at 12:28

Pyth, 10 bytes

jdmjkjCd2z

Python mapping and explanation:

j           # join(                               "Join by space"
 d          #      d,                             "this space"
 m          #      Pmap(lambda d:                 "Map characters of input string"
  j         #                    join(            "Join by empty string"
   k        #                        k,           "this empty string"
    j       #                        join(        "This is not a join, but a base conversion"
     C      #                             Pchr(   "Convert the character to ASCII"
      d     #                                  d  "this character"
            #                                 ),
     2      #                             2       "Convert to base 2"
            #                            )
            #                        ),
  z         #           z)))                      "mapping over the input string"

Input is the string that needs to be converted without the quotes.

Try it here

share|improve this answer
8  
Is asdfghjlkl also a valid pyth program? What does it do? –  flawr Jan 22 at 22:57
    
@flawr any harm in trying ? ;) –  Optimizer Jan 22 at 22:57
2  
@flawr That compiles to the python Psum(d).append(Pfilter(lambda T:gte(head(join(Plen(k),Plen()))))), whee d=' ' and k=''. So no, it is not valid at all. –  isaacg Jan 22 at 23:11
10  
@ericmark26 look around your room or office, and smash everything that you can find into your keyboard and see if it interprets. Figure out what it does, and then repeat with the next object. When you run out, try different rotations. –  globby Jan 23 at 5:35
2  
@ericmark26 I think the best way to get used to Pyth is to take some simple Python programs, and translate them into Pyth. –  isaacg Jan 23 at 18:47

Haskell, 65

m s=tail$do c<-s;' ':do j<-[6,5..0];show$mod(fromEnum c`div`2^j)2

heavy use of the list monad. it couldn't be converted to list comprehentions because the last statements weren't a return.

share|improve this answer

Cobra - 64

As a Lambda:

do(s='')=(for c as int in s get Convert.toString(c,2)).join(' ')
share|improve this answer

Perl, 23

Takes input from stdin. One byte added for -n command line switch, which has the effect of wrapping the code inside while (<>) { ... } (Thanks, @chilemagic!)

s/./printf"%b ",ord/ge

From the command line, this would work as follows:

$ echo 'Hello World!' | perl -ne 's/./printf"%b ",ord/ge'
share|improve this answer
1  
You don't need the parentheses around the arguments to split. –  KSFT Jan 22 at 23:23
1  
Actually, you don't need them around the arguments to printf, either. –  KSFT Jan 22 at 23:25
    
You're right! :-D –  squeamish ossifrage Jan 22 at 23:25
1  
perl -nE'say s/./printf"%b ",ord/gre' would count as 28 characters. 27 within the single quotes + 1 for the -n. –  chilemagic Jan 23 at 0:55
    
@chilemagic I must install Perl 6 some day... –  squeamish ossifrage Jan 23 at 9:49

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))));
share|improve this answer

Golang - 68

I'm new to Go and I'm not sure on the rules for counting characters in this language on here either.

Imports (11 bytes):

import"fmt"

Function (55 bytes):

func c(s string){for _,r:=range s{fmt.Printf("%b ",r)}}

You can run it here.

share|improve this answer

J - 9

1":#:3&u:

No idea how to make this in a row without doubling the length of the code, I need J gurus to tell me :)

1":#:3&u:'Hello world!'
1001000
1100101
1101100
1101100
1101111
0100000
1110111
1101111
1110010
1101100
1100100
0100001
share|improve this answer
1  
You can add ". to the beginning. It evaluates your result so it will be in one line and separated by spaces. Even shorter is to create base10 numbers with the base2 digits: 10#.#:3&u:. –  randomra Jan 23 at 11:53

Python 3, 41 bytes

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

Like KSFT's answer, but I thought I'd point out that, in addition to raw_input -> input, Python 3 also has an advantage here due to the splat for print.

share|improve this answer

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
}
share|improve this answer

Matlab

This is an anonymous function

f=@(x) dec2bin(char(x))

usage is f('Hello World').

Alternatively, if x is defined as the string Hello World! in the workspace, then just dec2bin(char(x)) will work.

share|improve this answer
    
I'm not sure about how to score this because I'm not sure how I can get the input. Any comments? –  David Jan 23 at 0:12
    
Why char? I think you mean dec2bin(x)-'0' –  Luis Mendo Jan 23 at 16:09
    
Because I'm not that clever! –  David Jan 24 at 4:34
    
My point is: char(x), when x is already a string, does nothing. So you can remove it to save some space. On the other hand, the result of dec2bin is a string, and I think the output should be numbers –  Luis Mendo Jan 24 at 11:24
    
I understand, and you are right, of course. Matlab makes it easy to forget about data types sometimes. –  David Jan 26 at 5:12

Python - 52

print" ".join([bin(ord(i))[2:]for i in raw_input()])

I'll work on translating this into Pyth. Someone else did a Pyth answer already.

If you don't care about it being a full program or about I/O format and use Python 3, you can do it in 23 bytes like this:

[bin(ord(i))for i in x]

x is the input.

I know this doesn't count because the interpreter wasn't released before the challenge was posted, but here it is in KSFTgolf:

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