String to Binary

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.

• We had the reversed asked: codegolf.stackexchange.com/questions/35096/… Jan 23 '15 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. Jan 23 '15 at 4:12
• 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. Jan 23 '15 at 4:22
• Does it has to be ASCII? i.e., if a technology is not ASCII compatible, could the results reflect that? Apr 13 '19 at 11:13
• Is it acceptable to output with a separator other than spaces (e.g. a newline)? Sep 3 '19 at 9:51

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.

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

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

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

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

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: "e" = 01 100 101: "l" = 01 101 100: Try it online!

Non-competing, of course. :)

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

Ruby, 3428 24 bytes

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

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

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

PowerShell, 6359 46 bytes

-13 bytes thanks to @mazzy

Try it online!

x86-16 machine code, IBM PC DOS, 3331 28 bytes

Binary:

00000000: d1ee ad8a c849 b308 ac92 b000 d0e2 1430  .....I.........0
00000010: cd29 4b75 f5b0 20cd 29e2 ebc3            .)Ku.. .)...

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
92          XCHG AX, DX         ; use DX for bit shift
LOOP_BIT:
B0 00       MOV  AL, 0          ; clear AL
D0 E2       SHL  DL, 1          ; high-order bit into CF
14 30       ADC  AL, '0'        ; AL = '0' + CF
CD 29       INT  29H            ; write AL to screen
4B          DEC  BX             ; decrement bit counter
75 F5       JNZ  LOOP_BIT       ; loop next bit
B0 20       MOV  AL, ' '        ; display a space
CD 29       INT  29H            ; write AL to screen
E2 EB       LOOP LOOP_CHAR      ; loop next char

A standalone PC DOS executable COM file. Input is via command line, output to screen. m s=tail$do c<-s;' ':do j<-[6,5..0];show$mod(fromEnum cdiv2^j)2

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

C++ - 119 bytes

Freeing memory? What's that?

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

(MSVC compiles the code with warning)

• C version, shorter main(int c,char**v){char x;for(;c=*(v++);printf("%s ",itoa(c,x,2)));} Jan 23 '15 at 12:28

OBK

Try it online!

Tcl, 52 bytes

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

Try it online!

APL (Dyalog), 12 bytes

10⊥2⊥⍣¯1⎕UCS

Try it online!

Thanks to Adám for help with this solution.

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. JavaScript ES6, 71 bytes

• Welcome to PPCG! You need .split('') to split at the empty string; .split() turns "abc" into ["abc"]. Apr 13 '19 at 1:55

><>, 34 bytes

i\~48*o
?\:0(?;:2%:}-2,:0=
?\{nl1=

Try it online!

05AB1E, 4 bytes

Çbðý

Try it online.

Explanation:

Ç     # Convert the (implicit) input-string to a list of unicode values
b    # Convert each integer to a binary string
ðý  # Join by spaces (and output the result implicitly)

Could be just the first two bytes if a list output is allowed, or 3 bytes with » if a newline delimiter instead of space delimiter is allowed.

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!

Python 3, 39 bytes

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

Try it online!

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

JavaScript (V8), 52 bytes

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

Try it online!