11
\$\begingroup\$

Yeah... it's confusing. Let me explain it a little better:

  1. With a string, get the unicode code points of each letter
    • Let's use "Hello World!".
    • The code points would be [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]
  2. Of each digit of the code points, get their binary format
    • Get the binary of 7, then 2, then 1, then 0, and so on...
    • ['111', '10', '1', '0', '1', '1', '0', '1000', ...]
  3. The binary integers are treated as decimal and summed, and that's the result.
    • Take the integer of the binary (e.g. '111' is the integer 111 in decimal; one hundred and one) then sum all of these integers.
    • The result of "Hello World!" would be 4389.

Test Cases

"Hello World!" -> 4389
"Foo Bar!" -> 1594
"Code Golf" -> 1375
"Stack Exchange" -> 8723
"Winter Bash" -> 2988

Shortest code in bytes wins!

\$\endgroup\$
5
  • \$\begingroup\$ May I assume input is non-empty? \$\endgroup\$
    – tsh
    Commented Dec 21, 2021 at 8:08
  • 7
    \$\begingroup\$ As the guts of the problem are the integer/binary manipulations will you accept an answer based on the the common ASCII/Unicode code points \$\endgroup\$
    – Graham
    Commented Dec 21, 2021 at 8:45
  • \$\begingroup\$ @tsh yes, there will be a string \$\endgroup\$ Commented Dec 21, 2021 at 17:19
  • \$\begingroup\$ @Graham yes, I will. As long as it works :D \$\endgroup\$ Commented Dec 21, 2021 at 17:19
  • \$\begingroup\$ Can we take input as an array of characters instead of a string? Not sure if that's allowed by default \$\endgroup\$ Commented Dec 22, 2021 at 13:48

33 Answers 33

8
\$\begingroup\$

05AB1E, 4 bytes

ÇSbO

Try it online!

Get the codepoints, split into digits, convert to binary, sum.

\$\endgroup\$
6
\$\begingroup\$

Jelly, 6 bytes

ODFBḌS

Try It Online!

Literally just ord → to digits → flatten → to binary → from decimal → sum

\$\endgroup\$
3
  • \$\begingroup\$ This makes no sense... how does it work??! \$\endgroup\$ Commented Dec 21, 2021 at 4:17
  • \$\begingroup\$ @12944qwerty added an explanation \$\endgroup\$
    – hyperneutrino
    Commented Dec 21, 2021 at 4:18
  • \$\begingroup\$ That actually looks really simplistic. Imma need to take a look at the language. \$\endgroup\$ Commented Dec 21, 2021 at 4:19
5
\$\begingroup\$

MathGolf, 8 bytes

▒$m▒─àiΣ

Try it online.

7 bytes by removing the leading and taking the input as a list of characters: try it online.

Explanation:

▒         # Convert the (implicit) input-string to a list of characters
 $        # Convert each character to its codepoint integer
  m       # Map over each integer:
   ▒      #  Convert it to a list of digits
    ─     # Flatten the list of lists
     à    # Convert each digit to a binary string
      i   # Convert each string to an integer
       Σ  # Sum them together
          # (after which the entire stack is output implicitly as result)
\$\endgroup\$
5
\$\begingroup\$

Wolfram Language (Mathematica), 62 bytes

Tr[FromDigits/@Join@@i@ToCharacterCode@#~i~2]&
i=IntegerDigits

Try it online!

-6 bytes from @att

\$\endgroup\$
1
  • \$\begingroup\$ 62 bytes \$\endgroup\$
    – att
    Commented Dec 23, 2021 at 5:43
4
\$\begingroup\$

Python 2, 61 bytes

lambda s:sum(int(bin(int(y))[2:])for x in s for y in`ord(x)`)

Try it online!

\$\endgroup\$
4
\$\begingroup\$

R, 87 83 bytes

Edit: -4 bytes magnanimously thanks to pajonk

function(s,e=7:0,`/`=Vectorize(function(x,b)x%/%b^e%%b))sum(utf8ToInt(s)/10/2*10^e)

Try it online!

Works for ASCII characters (codepoint ≤8 bits). Add 1 byte to handle up to 100-bit codepoints, by changing 7:0 to 99:0.

Ungolfed

g=Vectorize(                    # g is a vectorized helper function
 function(x,b)x%/%b^(7:0)%%b    # that converts x to base b digits
function(s){                    # get the string s
 c=utf8ToInt(s)                 # get the codepoints c
 d=g(c,10)                      # apply g with arg 10 => get decimal digits
 b=g(d,2)                       # apply g with arg 2 => get binary digits
 e=b*10^(7:0)                   # multiply binary digits by powers of 10
 sum(e)                         # return the sum
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Probably shouldn't do this, as this will leave me outgolfed... -4 bytes. \$\endgroup\$
    – pajonk
    Commented Dec 21, 2021 at 15:13
  • 1
    \$\begingroup\$ @pajonk - Great, and thanks. I'd tried Vectorize, but never thought of replacing the vectorized function for a binary operator. Really clever. \$\endgroup\$ Commented Dec 21, 2021 at 15:39
4
\$\begingroup\$

R, 100 97 85 79 bytes

Or R>=4.1, 72 bytes by replacing the word function with a \.

Edit: - 5 bytes by @Dominic van Essen with huge thanks and a fair play award.

function(s)sum(10^(0:31)*!intToBits(unlist(strsplit(c("",utf8ToInt(s)),'')))<1)

Try it online!

Strings, digit split, converting to binary? These are things R isn't great in. Thank goodness there aren't primes involved in this challenge...

\$\endgroup\$
3
  • 1
    \$\begingroup\$ +1 for 'thank goodness there aren't primes...' \$\endgroup\$ Commented Dec 21, 2021 at 13:33
  • 1
    \$\begingroup\$ Probably shouldn't do this, but... 80 bytes with some funky type conversion... \$\endgroup\$ Commented Dec 21, 2021 at 17:25
  • \$\begingroup\$ @DominicvanEssen - thanks a lot! I didn't know intToBits accepts strings, that was clever! \$\endgroup\$
    – pajonk
    Commented Dec 21, 2021 at 18:44
3
\$\begingroup\$

Vyxal 2.4.1 s, 6 bytes

Cṅfbvṅ

Try it Online!

C      # Charcodes 
 ṅf    # to digitlist
   b   # Each to binary
    vṅ # Each to integer
       # (s flag) Sum
\$\endgroup\$
3
\$\begingroup\$

Charcoal, 12 bytes

IΣIE⭆S℅ι⍘Iι²

Try it online! Link is to verbose version of code. Explanation:

     S          Input string
    ⭆           Map over characters and join
       ι        Current character
      ℅         Ordinal
   E            Map over digits
          ι     Current digit
         I      Cast to integer
        ⍘  ²    Convert to base `2`
  I             Cast to integer
 Σ              Take the sum
I               Cast to string
                Implicitly print
\$\endgroup\$
3
\$\begingroup\$

JavaScript (Node.js), 74 bytes

s=>eval([...s.replace(/./gu,c=>c.codePointAt()),0].join`..toString(2)*1+`)

Try it online!

Eval abuse ftw!!! -2 bytes thanks to Neil. -1 byte thanks to tsh.

\$\endgroup\$
6
  • 1
    \$\begingroup\$ [...s.replace(/./gu,c=>c.codePointAt()),0] saves four bytes, I think? \$\endgroup\$
    – Neil
    Commented Dec 21, 2021 at 4:40
  • \$\begingroup\$ @Neil Oh nice! 0, still needed at the start tho \$\endgroup\$
    – emanresu A
    Commented Dec 21, 2021 at 4:41
  • \$\begingroup\$ Sorry, I was originally working from a previous version, so I hadn't updated it correctly. \$\endgroup\$
    – Neil
    Commented Dec 21, 2021 at 4:44
  • \$\begingroup\$ All testcase are ASCII. Must we support higher code points using /u flag? \$\endgroup\$
    – tsh
    Commented Dec 21, 2021 at 8:02
  • \$\begingroup\$ @tsh I'm not sure, ask on the main question \$\endgroup\$
    – emanresu A
    Commented Dec 21, 2021 at 8:04
3
\$\begingroup\$

K (ngn/k), 11 bytes

+//10/2\10\

Try it online!

  • 10\ convert input string to a matrix of the digits of its byte representation
  • 2\ convert those digits to binary
  • 10/ treat those binary numbers as if they were in base 10 (e.g. treat 111 in binary as 111 in base-10)
  • +// take the sum
\$\endgroup\$
0
3
\$\begingroup\$

Python, 62 Bytes

Thanks to @U12-F̉͋̅̾̇orward

lambda p:sum(int(f'{int(d):b}')for i in p for d in'%s'%ord(i))

Attempt it online!

Python, 63 Bytes

Thanks to @att

lambda p:sum(int(f'{int(d):b}')for i in p for d in str(ord(i)))

Attempt it online!

Python, 70 Bytes

Thanks to @Unrelated String

lambda p:sum(int(f'{int(i):b}')for i in"".join(str(ord(i))for i in p))

Attempt it online!

Python, 77 Bytes

Just a bunch of comprehension

l=lambda p:sum(int(format(int(i),"b"))for i in"".join(str(ord(i))for i in p))

Attempt it online!

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

JavaScript (ES6), 82 bytes

s=>-[...s].flatMap(c=>[...c.codePointAt()+""]).reduce((n,x)=>n-(+x).toString(2),0)
\$\endgroup\$
2
\$\begingroup\$

Lua, 141 bytes

s=...t={}u=0 for i=1,#s do v=s:sub(i,i):byte()while v>=1 do n=v%10 v=v//10 b="0"while n>0 do b=(n&1)..b n=n>>1 end u=u+b//10 end end print(u)

Try it online!

Important The current version of Lua in TIO is 5.3, this causes the output to be shown with .0 as a floating point number, in Lua 5.4 the output is shown as an integer as expected.

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

Factor + math.text.utils math.unicode, 52 bytes

[ [ 1 digit-groups ] map-flat [ >bin dec> ] map Σ ]

Try it online!

                                ! "hi"
[ 1 digit-groups ] map-flat     ! { 4 0 1 5 0 1 }
[ >bin dec> ] map               ! { 100 0 1 101 0 1 }
Σ                               ! 203
\$\endgroup\$
2
\$\begingroup\$

Ruby, 55 bytes

->s{s.chars.sum{|c|c.ord.digits.sum{|d|("%b"%d).to_i}}}

Try it online!

\$\endgroup\$
1
  • 2
    \$\begingroup\$ 48 bytes as a full program, or 46 bytes if a floating-point sum is acceptable. \$\endgroup\$
    – Dingus
    Commented Dec 21, 2021 at 22:56
2
\$\begingroup\$

MATL, 8 bytes

oV!UYBUs

The online interpreter only works with ASCII, because of Octave limitations. For non-ASCII the offline interpreter on MATLAB gives the correct result.

Try it online! Or verify all test cases.

Explanation

o    % Implicit input. Convert to double, element-wise. This gives codepoints
V    % Convert to string representation. Gives a row vector of chars
!    % Transposse into a column vector of chars
U    % Interpret each row (that is, each char) as a number
YB   % Convert to binary chars. Gives 3- or 4-column matrix with chars '0', '1', ' '
U    % Interpret each row as a number. Gives a column vector
s    % Sum. Implicit display
\$\endgroup\$
2
\$\begingroup\$

Python3.7.4, 81 79 bytes

f=lambda x:sum([int(bin(int(i))[2:])for i in"".join([str(ord(j)) for j in x])])

I was able to remove 2 bytes thanks to caird coinheringaahing's suggestion.

You can try it online!

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

BQN, 39 bytesSBCS

{+´{0:0;(2|𝕩)+10×𝕊⌊𝕩÷2}¨'0'-˜∾•Fmt¨𝕩-@}

Run online!

From what I could muster, recursion was the shortest method to convert the things to proper decimal. Character arithmetic saves a lot as usual.

Explanation

{+´{0:0;(2|𝕩)+10×𝕊⌊𝕩÷2}¨'0'-˜∾•Fmt¨𝕩-@}
                                  𝕩-@  subtract null character from string
                            ∾•Fmt¨     join all codepoints into a string
                       '0'-˜           subtract zero character to get the digits
   {                  }¨               for each digit:
    0:0;                               if input is 0, return 0
        (2|𝕩)+10×𝕊⌊𝕩÷2                  otherwise,                   
                 𝕊⌊𝕩÷2                  recursive call with x // 2
              10×                       multiply with 10
        (2|𝕩)+                          add x % 2
 +´                                     sum the result
\$\endgroup\$
2
  • \$\begingroup\$ I understand what everything does except the inner function. A more detailed explanation would be great. \$\endgroup\$
    – DLosc
    Commented Dec 23, 2021 at 19:27
  • 1
    \$\begingroup\$ @DLosc hope the explanation helps. You may want to see Block headers. \$\endgroup\$
    – Razetime
    Commented Dec 24, 2021 at 3:06
2
\$\begingroup\$

Japt -mx, 6 bytes

Takes input as an array of characters.

c ì x¤

Try it

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

Vyxal d, 7 bytes

Cƛfbvṅ⌊

Try it Online!

Fun for the whole family.

Explained

Cƛfbvṅ⌊
C      # Character code of each letter
 ƛ     # to each letter code n:
  fb   #   get the binary representation of each digit
    vṅ⌊ #  and convert to int
       # the d flag deep sums the list.
\$\endgroup\$
4
  • \$\begingroup\$ This makes no sense... how does it work??! And how do you get the characters \$\endgroup\$ Commented Dec 21, 2021 at 4:18
  • \$\begingroup\$ @12944qwerty I use the on-screen keyboard provided on the vyxal online interpreter. \$\endgroup\$
    – lyxal
    Commented Dec 21, 2021 at 4:19
  • \$\begingroup\$ Where is the "d flag"? \$\endgroup\$ Commented Dec 21, 2021 at 4:20
  • \$\begingroup\$ @12944qwerty it's in the header of the answer. \$\endgroup\$
    – lyxal
    Commented Dec 21, 2021 at 4:20
1
\$\begingroup\$

Husk, 8 bytes

ṁodḋṁodc

Try it online!

(or ṁȯṁodḋdc TIO or ṁöṁdmḋdc TIO, all 8 bytes)

ap & flatten combination of decimal digits & character code functions; then ap & sum combination of decimal values from binary igits.

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

Japt -x, 8 bytes

mc ¨nA2

Try it

mc        - codepints
   ¨nA2  - digits to binary string

-x flag to sum
\$\endgroup\$
2
  • \$\begingroup\$ 7 bytes \$\endgroup\$
    – Shaggy
    Commented Dec 31, 2021 at 13:39
  • \$\begingroup\$ @Shaggy thanks! I'm gonna leave it as it is because you have your great answer. Happy New year mate cheers! \$\endgroup\$
    – AZTECCO
    Commented Dec 31, 2021 at 18:04
1
\$\begingroup\$

C (gcc), 100 89 bytes

m;b;r;d;f(char*s){for(r=0;d=*s++;)for(;d;d/=10)for(m=1,b=d%10;b;b/=2,m*=10)r+=b%2*m;d=r;}

Try it online!

Inputs a string and returns the sum of the binary numbers.

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

APL+WIN, 38 bytes

This assumes we are allowed an answer based on the the common ASCII/Unicode code points.

Index origin = 0. Prompts for string:

+/⍎¨(⍕¨⊂[1]⍉(4⍴2)⊤⍎¨(⍕⎕av⍳⎕)~' ')~¨' '

⎕av⍳ uses the APL atomic vector to retrieve the ASCII code points. 

I can only use TIO via Dyalog Classic APL and Dyalog's atomic vector is not identical to that of APL+WIN so that will not work for this solution. However for those who would like to try the integer/binary manipulation via TIO the code below prompts for the integer code points for all the examples given in the question and yields the appropriate sums.

+/⍎¨(⍕¨⊂[1]⍉(4⍴2)⊤⍎¨(⍕⎕)~' ')~¨' '

Try it online! Thanks to Dyalog Classic

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

APOL, 32 bytes

⊕(⭳(ƒ(i ƒ(Ŀ(t(↶(∋))) I(b(∋))))))

Explanation

⊕(                Sum (totals all items in a list)
  ⭳(              List flatten (Turns 2d lists into 1d lists)
    ƒ(            List-builder for (returns a list of every return value of the passed instruction during the loop
      i           Input (being iterated through
      ƒ(          List-builder for
        Ŀ(        Cast to int list (Splits a string and returns a list of each character as an integer
          t(      Cast to string
            ↶(    Unicode codepoint
               ∋  For loop item
            )
          )
        )
        I(        Cast to integer
          b(      Binary representation of
            ∋     For loop item
          )
        )
      )
    )
  )
)
\$\endgroup\$
1
\$\begingroup\$

Zsh, 61 bytes

for c (${(s'')1})for d (${(s'')$((#c))})T+=+$[[##2]d]
<<<$[T]

Try it online!

Nothing terribly interesting here, except that it saves 1 byte to do string appending and defer the final $[sum] until the last step.

for char (${(s'')1})                # split into characters
    for digit (${(s'')$((#char))})  # split decimal codepoint into characters
        sum_string+=+$[[##2]digit]  # append "+" and the binary representation to a string
<<<$[sum_string]                    # evaluate that string arithmetically, output
\$\endgroup\$
1
\$\begingroup\$

Haskell, 76 bytes

e=fromEnum
f s=sum$map(\x->read$(mapM id$"01"<$[0..3])!!(e x-48))$s>>=show.e

Try it online!

..s>>=show.e         - all digits of ascii values 
mapM id$"01"<$[0..3] - combinations of bits
!!(e x-48)           - take at (enum-48) and
map(\x->read$(...)   - read it for every digit
sum                  - sum 
\$\endgroup\$
1
\$\begingroup\$

PowerShell, 69[:(] 68 65 bytes

$args|% t*y|%{+$_-split''|%{$s+=+[Convert]::ToString("$_",2)}};$s

Try it online!

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

Pip, 10 bytes

$+TB*J A*a

Try it online!

Explanation

         a  First command-line argument (the input string)
       A    Get ASCII code
        *   of each character
     J      Join into a single string
  TB        Convert to binary
    *       each character (i.e. digit)
$+          Sum
\$\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.