# Convert the decimal digits of a string's Unicode codepoints to binary, reinterpret as decimal, and take the sum

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!

• May I assume input is non-empty?
– tsh
Dec 21, 2021 at 8:08
• 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 Dec 21, 2021 at 8:45
• @tsh yes, there will be a string Dec 21, 2021 at 17:19
• @Graham yes, I will. As long as it works :D Dec 21, 2021 at 17:19
• Can we take input as an array of characters instead of a string? Not sure if that's allowed by default Dec 22, 2021 at 13:48

# 05AB1E, 4 bytes

ÇSbO


Try it online!

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

# Jelly, 6 bytes

ODFBḌS


Try It Online!

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

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

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


# Wolfram Language (Mathematica), 62 bytes

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


Try it online!

-6 bytes from @att

• 62 bytes
– att
Dec 23, 2021 at 5:43

# Python 2, 61 bytes

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


Try it online!

# 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

• Probably shouldn't do this, as this will leave me outgolfed... -4 bytes. Dec 21, 2021 at 15:13
• @pajonk - Great, and thanks. I'd tried Vectorize, but never thought of replacing the vectorized function for a binary operator. Really clever. Dec 21, 2021 at 15:39

# R, 1009785 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...

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

# Vyxal 2.4.1s, 6 bytes

Cṅfbvṅ


Try it Online!

C      # Charcodes
ṅf    # to digitlist
b   # Each to binary
vṅ # Each to integer
# (s flag) Sum


# Charcoal, 12 bytes

ＩΣＩＥ⭆Ｓ℅ι⍘Ｉι²


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

     Ｓ          Input string
⭆           Map over characters and join
ι        Current character
℅         Ordinal
Ｅ            Map over digits
ι     Current digit
Ｉ      Cast to integer
⍘  ²    Convert to base 2
Ｉ             Cast to integer
Σ              Take the sum
Ｉ               Cast to string
Implicitly print


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

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

# 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

# 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!

# JavaScript (ES6), 82 bytes

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


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

# 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


# Ruby, 55 bytes

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


Try it online!

• 48 bytes as a full program, or 46 bytes if a floating-point sum is acceptable. Dec 21, 2021 at 22:56

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

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


# 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!

• Welcome to Code Golf, and nice first answer! You can save 2 bytes by removing the spaces between the ) and the fors, and one more by changing in "" to in"" Dec 22, 2021 at 1:16
• Thank you for the insight. Dec 22, 2021 at 1:18
• Dec 27, 2021 at 7:29

# 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
+´                                     sum the result

• I understand what everything does except the inner function. A more detailed explanation would be great. Dec 23, 2021 at 19:27
• @DLosc hope the explanation helps. You may want to see Block headers. Dec 24, 2021 at 3:06

# Japt-mx, 6 bytes

Takes input as an array of characters.

c ì x¤


Try it

# Vyxald, 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.

• This makes no sense... how does it work??! And how do you get the characters Dec 21, 2021 at 4:18
• @12944qwerty I use the on-screen keyboard provided on the vyxal online interpreter. Dec 21, 2021 at 4:19
• Where is the "d flag"? Dec 21, 2021 at 4:20
• @12944qwerty it's in the header of the answer. Dec 21, 2021 at 4:20

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

# Japt-x, 8 bytes

mc ¬®nA2


Try it

mc        - codepints
¬®nA2  - digits to binary string

-x flag to sum

• 7 bytes Dec 31, 2021 at 13:39
• @Shaggy thanks! I'm gonna leave it as it is because you have your great answer. Happy New year mate cheers! Dec 31, 2021 at 18:04

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

# 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

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


# 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  # 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  # PowerShell, 69[:(] 68 65 bytes $args|% t*y|%{+$_-split''|%{$s+=+[Convert]::ToString("$_",2)}};$s


Try it online!

# 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