String to Binary

19

3

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.

ericmarkmartin

Posted 2015-01-22T22:47:37.300

Reputation: 323

1I 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. – ericmarkmartin – 2015-01-23T04:12:50.380

1that'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. – hmatt1 – 2015-01-23T04:22:50.713

Can I take input via a file (as specified at http://meta.codegolf.stackexchange.com/a/2452/30076)?

– bmarks – 2015-01-23T16:08:47.367

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. – ericmarkmartin – 2015-01-27T18:05:47.393

Are the spaces necessary? – idrougge – 2017-11-02T14:25:12.730

1Does it has to be ASCII? i.e., if a technology is not ASCII compatible, could the results reflect that? – Shaun Bebbers – 2019-04-13T11:13:27.970

1Can we assume ASCII printable 32-127? If so, can binary strings be 7 chars with left zero-padding? – 640KB – 2019-04-15T15:29:07.670

1Is it acceptable to output with a separator other than spaces (e.g. a newline)? – caird coinheringaahing – 2019-09-03T09:51:43.047

Answers

13

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

Optimizer

Posted 2015-01-22T22:47:37.300

Reputation: 25 836

13

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.

Sp3000

Posted 2015-01-22T22:47:37.300

Reputation: 58 729

8

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

Optimizer

Posted 2015-01-22T22:47:37.300

Reputation: 25 836

10Is asdfghjlkl also a valid pyth program? What does it do? – flawr – 2015-01-22T22:57:00.643

@flawr any harm in trying ? ;) – Optimizer – 2015-01-22T22:57:22.527

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 – 2015-01-22T23:11:51.370

Thanks for the Pyth solution. I just started learning it today, but I think it will take some time getting used to. Any suggestions? – ericmarkmartin – 2015-01-23T04:09:06.897

12@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 – 2015-01-23T05:35:01.510

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 – 2015-01-23T18:47:18.777

4

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

matsjoyce

Posted 2015-01-22T22:47:37.300

Reputation: 1 319

3

PowerShell, 63 59 46 bytes

-13 bytes thanks to @mazzy

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

Try it online!

Gabriel Mills

Posted 2015-01-22T22:47:37.300

Reputation: 778

? Try it online!

– mazzy – 2019-04-13T20:47:24.763

3

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

KSFT

Posted 2015-01-22T22:47:37.300

Reputation: 1 527

3

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.

Martin Ender

Posted 2015-01-22T22:47:37.300

Reputation: 184 808

trim by 6 with $<.each_byte{|c|$><<"%b "%c} – AShelly – 2015-01-23T19:07:19.527

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 – 2015-01-23T22:16:14.763

@britishtea Oh, nice. thank you! – Martin Ender – 2015-01-23T22:55:08.393

2

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.

640KB

Posted 2015-01-22T22:47:37.300

Reputation: 7 149

2

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. :)

640KB

Posted 2015-01-22T22:47:37.300

Reputation: 7 149

2

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

NinjaBearMonkey

Posted 2015-01-22T22:47:37.300

Reputation: 9 925

1[for of] is slightly shorter than [...].map to enumerate charactes in strings: alert([for(c of prompt())c.charCodeAt().toString(2)].join(' ')) – edc65 – 2015-01-23T14:03:53.007

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 – RamenChef – 2017-11-01T15:44:24.993

2

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.

David

Posted 2015-01-22T22:47:37.300

Reputation: 1 316

I'm not sure about how to score this because I'm not sure how I can get the input. Any comments? – David – 2015-01-23T00:12:56.733

Why char? I think you mean dec2bin(x)-'0' – Luis Mendo – 2015-01-23T16:09:46.807

Because I'm not that clever! – David – 2015-01-24T04:34:53.247

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 – 2015-01-24T11:24:55.553

I understand, and you are right, of course. Matlab makes it easy to forget about data types sometimes. – David – 2015-01-26T05:12:36.473

2

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

swish

Posted 2015-01-22T22:47:37.300

Reputation: 7 484

2You 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 – 2015-01-23T11:53:07.453

2

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

Bryan Devaney

Posted 2015-01-22T22:47:37.300

Reputation: 51

2I think OP wants a full program, not just a snippet. Plus, it can be golfed a lot more, methinks. – Rodolfo Dias – 2015-01-23T11:47:53.733

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 – 2015-01-23T13:10:59.740

1The full program includes the main class, too. – Rodolfo Dias – 2015-01-23T13:19:05.637

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 – 2015-01-23T15:00:19.910

nice, I would never have thought of that. thank you. – Bryan Devaney – 2015-01-23T15:23:31.017

1You 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. – Rodolfo Dias – 2015-01-23T15:33:12.137

I know it's been more than 2.5 year, but you can save 20 bytes like this: interface B{static void main(String[]a){for(Integer i=0;i<a[0].length();)System.out.print(i.toString(a[0].charAt(i++),2)+" ");}} – Kevin Cruijssen – 2017-11-01T14:50:26.673

2

Scala - 59 - 55 Bytes

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

Normally, one should use foreach and not map.

Dominik Müller

Posted 2015-01-22T22:47:37.300

Reputation: 131

1

Tcl, 52 bytes

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

Try it online!

sergiol

Posted 2015-01-22T22:47:37.300

Reputation: 3 055

Unfortunately the program version has more bytes due to the join: binary scan [join $argv] B* b;puts [regsub -all .{8} $b {& }]

– sergiol – 2017-11-01T12:10:59.137

1

Jelly, 3 bytes

OBK

Try it online!

Erik the Outgolfer

Posted 2015-01-22T22:47:37.300

Reputation: 38 134

1

APL (Dyalog), 12 bytes

10⊥2⊥⍣¯1⎕UCS

Try it online!

Thanks to Adám for help with this solution.

Erik the Outgolfer

Posted 2015-01-22T22:47:37.300

Reputation: 38 134

1

Python 3.6, 39 bytes

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

Try it online!

ovs

Posted 2015-01-22T22:47:37.300

Reputation: 21 408

1

JavaScript ES6, 71 bytes

alert(prompt().split('').map(c=>c.charCodeAt(0).toString(2))).join(' ')

thomascorthouts

Posted 2015-01-22T22:47:37.300

Reputation: 11

Welcome to PPCG! You need .split('') to split at the empty string; .split() turns "abc" into ["abc"]. – Dennis – 2019-04-13T01:55:31.193

1

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

Shaun Bebbers

Posted 2015-01-22T22:47:37.300

Reputation: 1 814

1

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

reffu

Posted 2015-01-22T22:47:37.300

Reputation: 1 361

1

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!

Jordan

Posted 2015-01-22T22:47:37.300

Reputation: 5 001

1

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!

EdgyNerd

Posted 2015-01-22T22:47:37.300

Reputation: 1 106

1

Python 3, 39 bytes

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

Try it online!

Slight improvement over the current leading Python answer

Jitse

Posted 2015-01-22T22:47:37.300

Reputation: 3 566

1

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

chrispsn

Posted 2015-01-22T22:47:37.300

Reputation: 11

1

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)

BMac

Posted 2015-01-22T22:47:37.300

Reputation: 2 118

1C 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̷̰̀ĥ̷̳ – 2015-01-23T12:28:30.590

1

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.

proud haskeller

Posted 2015-01-22T22:47:37.300

Reputation: 5 866

0

Julia, 23 bytes

f(n)=[bin(a)for a in n]

EricShermanCS

Posted 2015-01-22T22:47:37.300

Reputation: 121

0

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 " "

streetster

Posted 2015-01-22T22:47:37.300

Reputation: 3 635

0

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]

Joe

Posted 2015-01-22T22:47:37.300

Reputation: 895

0

PHP, 59 bytes

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

Try it online!

Jo.

Posted 2015-01-22T22:47:37.300

Reputation: 974

0

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

caird coinheringaahing

Posted 2015-01-22T22:47:37.300

Reputation: 13 702

0

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!

Benjamin Urquhart

Posted 2015-01-22T22:47:37.300

Reputation: 1 262

I'm so tired right now that I forgot I already did this challenge and almost posted a duplicate. – Benjamin Urquhart – 2019-04-16T12:32:32.943

0

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

Shaggy

Posted 2015-01-22T22:47:37.300

Reputation: 24 623

0

><>, 34 bytes

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

Try it online!

Emigna

Posted 2015-01-22T22:47:37.300

Reputation: 50 798

0

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.

Kevin Cruijssen

Posted 2015-01-22T22:47:37.300

Reputation: 67 575

0

Perl 5, 21 bytes

printf'%b ',ord for@F

Try it online!

Xcali

Posted 2015-01-22T22:47:37.300

Reputation: 7 671

0

Perl 6, 16 bytes

*.ords>>.base(2)

Try it online!

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

Jo King

Posted 2015-01-22T22:47:37.300

Reputation: 38 234

0

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!

Elcan

Posted 2015-01-22T22:47:37.300

Reputation: 913

0

Zsh, 43 bytes

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

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. 2#1001000)
                        ${           #??}     # strip leading two characters (e.g. 1001000)
                 printf ${              }\    # append space, print

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

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

Try it online!

GammaFunction

Posted 2015-01-22T22:47:37.300

Reputation: 2 838

using printf for 43 bytes

– roblogic – 2019-09-03T00:23:31.987

0

Python 3, 39 bytes

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

Try it online!

Divy

Posted 2015-01-22T22:47:37.300

Reputation: 51

1

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.

– caird coinheringaahing – 2019-09-03T09:51:08.820

0

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

Hauleth

Posted 2015-01-22T22:47:37.300

Reputation: 1 472

0

Erlang 41

[io:fwrite('~.2B ',[C])||C<-io:read("")].

Hauleth

Posted 2015-01-22T22:47:37.300

Reputation: 1 472

How is this answer called? Is it a complete program? Is it a function? Is it something else? – Post Rock Garf Hunter – 2019-09-03T18:35:03.280

Fixed to be full program. – Hauleth – 2019-09-04T16:57:22.800

0

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 

DeathIncarnate

Posted 2015-01-22T22:47:37.300

Reputation: 916

0

PHP, 44 bytes

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

Try it online!

640KB

Posted 2015-01-22T22:47:37.300

Reputation: 7 149

0

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
}

bmarks

Posted 2015-01-22T22:47:37.300

Reputation: 2 114

0

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.

hmatt1

Posted 2015-01-22T22:47:37.300

Reputation: 3 356

You can golf this with import."fmt" and then just using Printf. – S.S. Anne – 2020-02-21T23:56:05.830

0

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]).

c.P.u1

Posted 2015-01-22T22:47:37.300

Reputation: 1 049

0

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

Abbas

Posted 2015-01-22T22:47:37.300

Reputation: 349

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 – Skidsdev – 2019-04-15T15:09:28.480

Here's the lambda function solution using Interactive Compiler, total of 55 bytes – Skidsdev – 2019-04-15T15:10:15.543

0

Cobra - 64

As a Lambda:

do(s='')=(for c as int in s get Convert.toString(c,2)).join(' ')

Οurous

Posted 2015-01-22T22:47:37.300

Reputation: 7 916

0

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

AJMansfield

Posted 2015-01-22T22:47:37.300

Reputation: 2 758

0

JavaScript 78

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

wolfhammer

Posted 2015-01-22T22:47:37.300

Reputation: 1 219

0

Ruby 38 Bytes

p gets.bytes.map{|i|i.to_s 2}.join ' '

kyle k

Posted 2015-01-22T22:47:37.300

Reputation: 409

.join ' ' can be shortened to *' '. – Martin Ender – 2015-01-23T22:59:10.660