19
\$\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\$
  • 1
    \$\begingroup\$ We had the reversed asked: codegolf.stackexchange.com/questions/35096/… \$\endgroup\$ – hmatt1 Jan 23 '15 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\$ – ericmarkmartin Jan 23 '15 at 4:12
  • 1
    \$\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 Jan 23 '15 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\$ – Shaun Bebbers Apr 13 at 11:13
  • 1
    \$\begingroup\$ Can we assume ASCII printable 32-127? If so, can binary strings be 7 chars with left zero-padding? \$\endgroup\$ – 640KB Apr 15 at 15:29

50 Answers 50

13
\$\begingroup\$

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

\$\endgroup\$
13
\$\begingroup\$

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.

\$\endgroup\$
8
\$\begingroup\$

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

\$\endgroup\$
  • 10
    \$\begingroup\$ Is asdfghjlkl also a valid pyth program? What does it do? \$\endgroup\$ – flawr Jan 22 '15 at 22:57
  • \$\begingroup\$ @flawr any harm in trying ? ;) \$\endgroup\$ – Optimizer Jan 22 '15 at 22:57
  • 2
    \$\begingroup\$ @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. \$\endgroup\$ – isaacg Jan 22 '15 at 23:11
  • 12
    \$\begingroup\$ @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. \$\endgroup\$ – globby Jan 23 '15 at 5:35
  • 2
    \$\begingroup\$ @ericmark26 I think the best way to get used to Pyth is to take some simple Python programs, and translate them into Pyth. \$\endgroup\$ – isaacg Jan 23 '15 at 18:47
4
\$\begingroup\$

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()))
\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ trim by 6 with $<.each_byte{|c|$><<"%b "%c} \$\endgroup\$ – AShelly Jan 23 '15 at 19:07
  • \$\begingroup\$ 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 :) \$\endgroup\$ – britishtea Jan 23 '15 at 22:16
  • \$\begingroup\$ @britishtea Oh, nice. thank you! \$\endgroup\$ – Martin Ender Jan 23 '15 at 22:55
3
\$\begingroup\$

PowerShell, 63 59 46 bytes

-13 bytes thanks to @mazzy

"$($args|% t*y|%{[Convert]::ToString(+$_,2)})"

Try it online!

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

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.

\$\endgroup\$
  • \$\begingroup\$ I'm not sure about how to score this because I'm not sure how I can get the input. Any comments? \$\endgroup\$ – David Jan 23 '15 at 0:12
  • \$\begingroup\$ Why char? I think you mean dec2bin(x)-'0' \$\endgroup\$ – Luis Mendo Jan 23 '15 at 16:09
  • \$\begingroup\$ Because I'm not that clever! \$\endgroup\$ – David Jan 24 '15 at 4:34
  • \$\begingroup\$ 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 \$\endgroup\$ – Luis Mendo Jan 24 '15 at 11:24
  • \$\begingroup\$ I understand, and you are right, of course. Matlab makes it easy to forget about data types sometimes. \$\endgroup\$ – David Jan 26 '15 at 5:12
2
\$\begingroup\$

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
\$\endgroup\$
  • 2
    \$\begingroup\$ 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:. \$\endgroup\$ – randomra Jan 23 '15 at 11:53
2
\$\begingroup\$

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

\$\endgroup\$
  • 2
    \$\begingroup\$ I think OP wants a full program, not just a snippet. Plus, it can be golfed a lot more, methinks. \$\endgroup\$ – Rodolfo Dias Jan 23 '15 at 11:47
  • \$\begingroup\$ 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. \$\endgroup\$ – Bryan Devaney Jan 23 '15 at 13:10
  • 1
    \$\begingroup\$ The full program includes the main class, too. \$\endgroup\$ – Rodolfo Dias Jan 23 '15 at 13:19
  • \$\begingroup\$ 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 \$\endgroup\$ – njzk2 Jan 23 '15 at 15:00
  • 1
    \$\begingroup\$ You can get rid of the public and shorten the program name to a single char to win more bytes. Plus, (String[]a)is perfectly accepted by the compiler, earning you another byte. \$\endgroup\$ – Rodolfo Dias Jan 23 '15 at 15:33
2
\$\begingroup\$

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(' '))

\$\endgroup\$
  • 1
    \$\begingroup\$ [for of] is slightly shorter than [...].map to enumerate charactes in strings: alert([for(c of prompt())c.charCodeAt().toString(2)].join(' ')) \$\endgroup\$ – edc65 Jan 23 '15 at 14:03
  • \$\begingroup\$ You can golf off two bytes by replacing .join(' ') with .join` ` . You can golf off a lot of bytes by using a function instead of prompt/alert \$\endgroup\$ – RamenChef Nov 1 '17 at 15:44
2
\$\begingroup\$

Scala - 59 - 55 Bytes

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

Normally, one should use foreach and not map.

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

8088 machine code, IBM PC DOS, 33 31 bytes*

Listing:

D1 EE           SHR  SI, 1          ; point SI to DOS PSP (80H)
AD              LODSW               ; load input string length into AL, SI to 82H 
8A C8           MOV  CL, AL         ; set up loop counter 
49              DEC  CX             ; remove leading space/slash from char count 
            LOOP_CHAR: 
B3 08           MOV  BL, 8          ; loop 8 bits 
AC              LODSB               ; load next char 
            LOOP_BIT: 
D0 C0           ROL  AL, 1          ; high-order bit into low-order bit 
B4 0E           MOV  AH, 0EH        ; BIOS display character function 
50              PUSH AX             ; save AH/AL 
24 01           AND  AL, 1          ; mask all but low-order bit 
04 30           ADD  AL, '0'        ; convert to ASCII 
CD 10           INT  10H            ; write char to display 
58              POP  AX             ; restore AH/AL 
4B              DEC  BX             ; decrement bit counter 
75 F1           JNZ  LOOP_BIT       ; loop next bit      
B0 20           MOV  AL, ' '        ; display a space 
CD 10           INT  10H            ; write space to display 
E2 E8           LOOP LOOP_CHAR      ; loop next char 
C3              RET                 ; return to DOS 

Complete PC DOS executable COM file, input is via command line.

With leading zeros:

enter image description here

Download and test ASCBIN.COM.

Or 39 bytes without leading zeros:

enter image description here

Download and test ASCBIN2.COM.

*Since it wasn't explicitly clear to me whether or not leading zeros are allowed, am posting versions both ways.

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

MITS Altair 8800, 0 bytes

Input string is at memory address #0000H (allowed). Output in binary via front panel I/O lights D7-D0.

Example, do RESET, then EXAMINE to see the first byte, followed by repeating EXAMINE NEXT to see the rest.

"H" = 01 001 000:

enter image description here

"e" = 01 100 101:

enter image description here

"l" = 01 101 100:

enter image description here

Try it online!

Non-competing, of course. :)

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

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.

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

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)

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

Jelly, 3 bytes

OBK

Try it online!

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

Tcl, 52 bytes

proc B s {binary s $s B* b;regsub -all .{8} $b {& }}

Try it online!

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

APL (Dyalog), 12 bytes

10⊥2⊥⍣¯1⎕UCS

Try it online!

Thanks to Adám for help with this solution.

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

Python 3.6, 39 bytes

print(*[f'{ord(c):b}'for c in input()])

Try it online!

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

Commodore VIC-20/C64/128 and TheC64Mini, 101 tokenized BASIC bytes

Here is the obfuscated listing using Commodore BASIC keyword abbreviations:

 0dEfnb(x)=sG(xaNb):inputa$:fOi=1tolen(a$):b=64:c$=mI(a$,i,1):fOj=0to6
 1?rI(str$(fnb(aS(c$))),1);:b=b/2:nEj:?" ";:nE

Here for explanation purposes is the non-obfuscated symbolic listing:

 0 def fn b(x)=sgn(x and b)
 1 input a$
 2 for i=1 to len(a$)
 3 let b=64
 4 let c$=mid$(a$,i,1)
 5 for j=0 to 6
 6 print right$(str$(fn b(asc(c$))),1);
 7 let b=b/2
 8 next j
 9 print " ";
10 next i

The function fn b declared on line zero accepts a numeric parameter of x which is ANDed with the value of b; SGN is then used to convert x and b to 1 or 0.

Line one accept a string input to the variable a$, and the loop starts (denoted with i) to the length of that input. b represents each bit from the 6th to 0th bit. c$ takes each character of the string at position i.

line 5 starts the loop to test each bit position; right$ is used in line 6 to remove a auto-formatting issue when Commodore BASIC displays a number, converting the output of fn b to a string; asc(c$) converts the current character to its ascii code as a decimal value.

Line 7 represents the next bit value. The loop j is ended before printing a space, then the last loop i is ended.

C64 converting PETSCII to Binary

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

JavaScript ES6, 71 bytes

alert(prompt().split('').map(c=>c.charCodeAt(0).toString(2))).join(' ')
\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG! You need .split('') to split at the empty string; .split() turns "abc" into ["abc"]. \$\endgroup\$ – Dennis Apr 13 at 1:55
1
\$\begingroup\$

Forth (gforth), 45 bytes

: f 0 do dup i + c@ 2 base ! . decimal loop ;

Try it online!

Code Explanation

: f           \ start a new word definition
  0 do        \ start a loop from 0 to string length - 1
    dup i +   \ duplicate the address and add the loop index to get addr of current character
    c@        \ get the character at that address
    2 base !  \ set the base to binary
    .         \ print the ascii value (in binary)
    decimal   \ set the base back to decimal
  loop        \ end the loop
;             \ end the word definition
\$\endgroup\$
1
\$\begingroup\$

Ruby, 24 bytes

I was hoping to beat Martin Ender, but I only managed to tie him.

Takes input on STDIN; +1 bytes for -p flag.

gsub(/./){"%b "%$&.ord}

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\$

Python 3, 39 bytes

print(*[f'{ord(i):b}'for i in input()])

Try it online!

Slight improvement over the current leading Python answer

\$\endgroup\$
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\$

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.

\$\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\$
  • \$\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\$ – Skidsdev Apr 15 at 15:09
  • \$\begingroup\$ Here's the lambda function solution using Interactive Compiler, total of 55 bytes \$\endgroup\$ – Skidsdev Apr 15 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\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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