# What?

Many programming languages, both practical and esoteric, have functions, methods, etc to convert a given string to a decimal number. This is how the process might work:

• For each character in the given string.
• Take the character's ASCII value and subtract it by 48.
• Multiply the output value by 10. (The output at the first iteration is 0)
• Add the subtracted ASCII value to the output.

Let us do this process for the string "109":

1. The ASCII value of 1 is 49. Subtract it by 48, and we get 1. We multiply the output by 10, we get 0. Finally, we add 1 to 0 and get one.

2. Next, we subtract 0's ASCII value (48) by 48, we get 0. We multiply 1 by 10, we get 10. Nothing happens when we add 0.

3. Then we subtract 9's ASCII value (57) by 48, we get 9. We multiply 10 by 10 and get 100. We add 9 to 100 and get 109.

There, we successfully converted "109" to 109! It is just as simple!

The problem is that most languages do not like it when the converting string has non-digital characters (characters with an ASCII value not in the range 48-57 inclusive). They would most likely throw some nasty errors or exceptions at us.

How 'bout we ignore that!

Given a printable string from STDIN (you can assume that $$\1 ≤ \text{Input Length} ≤ 10\$$), implement a program or function to badly convert it to an integer according to the above steps, and output or return it back.

Strings can contain whitespace characters (Spaces, tabs and linefeeds).

For another example string "Hi!":

1. The ASCII value of H is 72:
72 - 48 = 24
0 * 10 = 0
0 + 24 = 24

2. The ASCII value of i is 105:
105 - 48 = 57
24 * 10 = 240
240 + 57 = 297.

3. The ASCII value of ! is 33:
33 - 48 = -15
297 * 10 = 2970
2970 + -15 = 2955

This means that "Hi!" converted to an integer is 2955!

Standard I/O rules apply.

Note: if your language does not support input, feel free to tell me in your answers (you can put the "input" strings in your source code)!

# More test cases

STDIN                  Output
"123456789"         ->  123456789
"0123456789"        ->  123456789
"-12345"            -> -287655
"Lorem"             ->  350191
"Ipsum"             ->  321451
"AAAAAAAA"          ->  188888887
"        "          -> -177777776
"A"                 ->  17
" "                 -> -16
"
"                   -> -38


Standard rules apply!

• What do you mean when you say "You can use Unicode values instead"? Unicode and ASCII code points line up, so there's no difference between Unicode and ASCII values Commented Oct 11, 2020 at 14:40
• Yes, but unless we have to handle inputs with characters outside of the printable ASCII range, the two are one and the same Commented Oct 11, 2020 at 14:55
• Just to confirm: "-12345" should convert to -287655? We don't want the conversion to be too perfect, correct? :-) Commented Oct 11, 2020 at 17:28
• Wouldn't it make more sense to switch the first two steps and replace "multiply the output" by "multiply the previous output (if available)"? No special case anymore, a better flow and no 10*1=0. Commented Oct 12, 2020 at 1:17
• @SunnyMoon: Sorry if I wasn't clear. I was just proposing an alternative way to explain the above process, because the current explanation is a bit confusing IMHO. "Multiply the output by 10 " seems to be referring to ASCII value - 48 even though it actually refers to the previous step. Just my 2c$, feel free to ignore it. Commented Oct 12, 2020 at 11:19 ## 57 Answers # Shakespeare Programming Language, 258 252 bytes -6 bytes thanks to the default. ,.Ajax,.Puck,.Act I:.Scene I:.[Exeunt][Enter Ajax and Puck] Ajax:Open mind. Puck:Is I nicer zero?If soYou is the sum ofI twice the difference betweenthe product ofyou the sum ofa cat a big big cat the factorial ofa big big cat. If soLet usAct I.Open heart  Try it online! The golfiest representation of the integer 48 is as twice the factorial of a big big cat, i.e. $$\48=2\times (2\times2\times1)!\$$. This corresponds to Ajax = 0 Puck = 0 Begin Act I Puck = read_input (as ASCII codepoint value) if(Puck>0){ Ajax = Puck + 2 * (Ajax * (4+1) - 4!) Go to Act I } print(Ajax) (as an integer)  • 252 bytes by rearranging the code to reuse twice: Try it online! Commented Oct 12, 2020 at 5:07 • @thedefault. Nice, thanks! Commented Oct 13, 2020 at 7:35 • a big big cat ... – matt Commented Oct 13, 2020 at 20:18 # Jelly, 5 bytes O_48Ḍ  Try it online! ## How it works O_48Ḍ - Main link. Takes a string s on the left O - Convert to ordinal code points _48 - Subtract 48 from each Ḍ - Convert from base-10  • Would the downvoter mind explaining why they cast their vote? This is a perfectly valid answer Commented Oct 11, 2020 at 15:31 # MATL, 8 bytes As long as we're doing things wrong, why not turn a string into a polynomial? 48-[X]ZQ  Try it online! Evaluates the polynomial $$p_1x^{n-1} + \cdots + p_{n-1}x^1 + p_nx^0$$ where $$\p\$$ is the input string (minus '0') and $$\x\$$ is 10. # Poetic, 153 bytes decoding a num got WRONG I/O digits i get?converting fails,o darn i am bummed if the I/O fails i have a number i got based on counting it badly,i suppose  Try it online! • I tried to run it online and it says: { ERROR: Unexpected EOF Done. Commented Oct 14, 2020 at 16:37 • Output is in the form of an ASCII byte. That is the byte with the ASCII value of 123. Commented Oct 14, 2020 at 23:01 # JavaScript (ES6/2015), 43 bytes s=>s.map(c=>r=r*10+c.charCodeAt()-48,r=0)|r  let f = s=>s.map(c=>r=r*10+c.charCodeAt()-48,r=0)|r console.log(f([..."123456789" ])) // 123456789 console.log(f([..."0123456789"])) // 123456789 console.log(f([..."Lorem" ])) // 350191 console.log(f([..."Ipsum" ])) // 321451 console.log(f([..."AAAAAAAA" ])) // 188888887 console.log(f([..." " ])) // -177777776 console.log(f([..."A" ])) // 17 console.log(f([..." " ])) // -16 Try it online! Edit #1: -1 byte thanks to l4m2 Edit #2: -7 bytes thanks to EzioMercer • Nice first answer! (Welcome to the site, by the way!) Commented Oct 14, 2020 at 1:53 • c.charCodeAt default para 0 – l4m2 Commented Jan 18, 2023 at 15:10 • You can reduce bytes count by 7 if use characters array instead of string tio.run/… Commented Jan 27, 2023 at 10:00 • @EzioMercer It conflicts with the assignment where is written that the function takes a string, but you gave me an idea, thanks for that Commented Jan 27, 2023 at 10:10 • No it doesn't, There are languages where isn't string type so they must use characters array. See: codegolf.meta.stackexchange.com/questions/2214/whats-a-string/…. You also can use characters array just specify it in your answer Commented Jan 27, 2023 at 10:16 # R, 51 48 bytes Edit: -3 bytes thanks to Robin Ryder function(s)(utf8ToInt(s)-48)%*%10^(nchar(s):1-1)  Try it online! Multiplies Utf8 value of each character minus 48 by powers-of-ten from the length of the string minus one, down to zero, and outputs the sum. • Wow! You answered in just about 10 minutes after the release of this question! Commented Oct 11, 2020 at 13:54 • R is usually quite bad for text-based challenges, but the vectorization helps a lot here... Commented Oct 11, 2020 at 13:56 • Does R have a convert to base 10 builtin? That‘s essentially what the step is after subtracting 48, so that may be shorter than vectorising over the powers and summing Commented Oct 11, 2020 at 14:13 • There are no base conversion builtins, but you can save 3 bytes thanks to vector multiplication: Try it online! Commented Oct 11, 2020 at 21:58 • @cairdcoinheringaahing there is strtoi but it forces you to just use 0-9a-z so it wouldn't be of any help here. I'm pretty sure this is as short as this can get. Commented Oct 12, 2020 at 19:08 # Python 3, 4645 42 bytes f=lambda s:s>[]and ord(s.pop())-48+10*f(s)  Try it online! -1 thanks to Sisyphus -3 taking a list of characters as input thanks to ovs # Scala, 18 bytes _./:(0)(_*10+_-48)  Try it online! Explanation: _./:(0)(_*10+_-48) /: Fold left _ the input string (0) with an initial value of 0 (_*10+_-48) Multiply the accumulator by 10, and add the next character - 48  • awesome answer! Commented Oct 15, 2020 at 17:54 # Brachylog, 13 bytes ạ-₄₈ᵐ{×₁₀ʰ+}ˡ  Try it online! For single-"digit" inputs, the output is wrapped in a list, since the fold isn't actually executed. If this isn't acceptable, two 15-byte alternatives exist: ạ-₄₈ᵐ,0↻{×₁₀ʰ+}ˡ ạ↔-₄₈ᵐ{i×₁₀ⁱ⁾}ᶠ+ ạ Convert to codepoints. -₄₈ᵐ Subtract 48 from each. { }ˡ Left fold: ×₁₀ʰ multiply the accumulator (initialized to first element) by 10 + and add it to the next element.  Brachylog's base conversion builtin actually disallows values outside the usual range, because it's actually quite useful sometimes on top of preserving proper inverse behavior, so I'm forced to implement the described algorithm directly. # PowerShell Core, 35 26 bytes $args|%{$r=$r*10+$_-48}$r


Saved 9 bytes using splatting

Try it online!

• Welcome to the site and nice first answer! Be sure to check out our Tips for golfing in Powershell page Commented Oct 11, 2020 at 19:54

# APL (Dyalog Unicode), 11 bytes

10⊥48-⍨⎕UCS


Try it online!

⎕UCS converts string to a vector of ASCII values, 48-⍨ subtracts 48 from each value and 10⊥ converts from base 10.

# Java 8, 46 bytes

a->{int r=0;for(var c:a)r=r*10+c-48;return r;}


Input as a character-array.

Try it online.

Explanation:

a->{            // Method with character-array parameter and integer return-type
int r=0;      //  Result-integer, starting at 0
for(var c:a)  //  Loop over the input-characters:
r=          //   Change the result to:
r*10      //    The current result multiplied by 10
+c-48;    //    And add the codepoint of the current characters minus 48
return r;}    //  After the loop, return the result


n#(h:t)=(n*10+fromEnum h-48)#t
n#_=n
f=(0#)


Try it online!

n#(h:t)=       - # -> infix function taking a number and a string(head:tail)
- compute first char and call recursively on tail

n#_=n          - end condition

f=(0#)         - apply 0 to #

• User 榨 菜 suggested this edit to save 11 bytes Commented Oct 13, 2020 at 21:52

# Vyxal, 5 bytes

C48-I


Try it Online!

Wow it's actually ASCII.

# Assembly (NASM, 32-bit, Linux), 221185 147 bytes

Edit: -36 bytes + bugfix

Edit: -38 bytes

mov edi,0
push 48
l:imul edi,edi,10
sub edi,48
mov edx,1
mov ecx,esp
mov ebx,0
mov eax,3
int 128
mov ax,[esp]
xor ax,10
jnz l
pop eax


Try it Online!

The result is in edi.

# Stax, 7 bytes

ëk╜ΓOíU


Run and debug it

Explanation:

{48-mA|E Unpacked source, implicit input
{   m    Map over code points of input string
48-       Subtract 48 from each
A|E Convert from base 10


# Perl 5, 40 bytes

sub{my$r;map$r=$r.0-48+ord,pop=~/./g;$r}


Try it online!

• 22 bytes Try it online! Commented Oct 11, 2020 at 15:40
• @NahuelFouilleul Nice!!! 👍 Commented Oct 11, 2020 at 15:45

# C (gcc), 48 44 bytes

Usually using a temporary variable to store the current character is shorter than doing array processing, but not this time!

i;f(char*s){for(i=0;*s;i=i*10+*s++-48);s=i;}


Try it online!

# J, 12 bytes

10#._48+3&u:


Try it online!

# Python 3, 53 bytes

def f(x):
o=0
for i in x:o=o*10+ord(i)-48
return o


Try it online!

• You can shorten this to 45 if you switch to Python 2 + a full program: Try it online! Commented Oct 12, 2020 at 0:56
• @Sisyphus am I wrong, or does switching to Python 2 only save a single byte? Commented Oct 13, 2020 at 20:05
• @MarkRansom You're not wrong! The full program gets you to 46, and switching to Python 2 gets you to 45. Commented Oct 13, 2020 at 23:16

# JavaScript (Node.js),  39  38 bytes

Saved 1 byte thanks to @Shaggy

s=>Buffer(s).map(c=>p=p*10+c-48,p=0)|p


Try it online!

• Would map not be shorter? Commented Oct 11, 2020 at 19:45
• @Shaggy Not any way I can think of. You'd have to manually change an accumulator with map, while reduce has that built in. Commented Oct 11, 2020 at 21:09
• s=>Buffer(s).map(c=>p=p*10+c-48,p=0)|p should do it. Commented Oct 11, 2020 at 21:29

# K (ngn/k), 7 bytes

10/-48+


Try it online!

# brainfuck, 43 38 bytes

,[<[>++++++++++<-]>+++>+[<->+++++],]<.


Try it online!

Thanks to JosiahRyanW for -5 bytes.

Since by our consensus, output can be given as character code, this is pretty straightforward in brainfuck. Note that the brainfuck interpreter on tio.run has 8-bit wrapping cells, so the maximum value is 255.

,[                  while input
<[>++++++++++<-]  add 10 times previous sum to input
>+++>+[<->+++++]  add 208 to it (effectively subtracting 48 by 8 bit wrapping)
]
<.                  output

• ,[+++<[>++++++++++<-]>>+[<->+++++],]<. is 38 bytes (assumes 8-bit wrapping cells). Commented Oct 12, 2020 at 7:09
• That"s surprisingly concise, if not readable. Commented Oct 12, 2020 at 18:08

# Befunge-98 (PyFunge), 14 12 bytes

Thanks to Gegell for -2 bytes!

2j@.~'0-\a*+


Try it online!

Explanation:

Initially the instruction pointer (IP) is moving right and the stack is filled with 0's.
2j skips the next two instruction (@.).
~ reads one character of input.
'0- subtracts 48 from the input.
\ swaps the two elements at the top of the stack. Now the intermediate result is on the top.
a* multiplies the result by 10.
+ adds the new number.
After that the IP wraps around to process the next character.

If there is no input left ~ reflects the IP.
. prints the result at the top of the stack, and @ terminates the program.

Animation of the code with input Lorem:

I'm not sure why there are black bars on two frames, I blame ImageMagick :/

• Instead of using movement redirection and the newline (that is also counted as an additional byte) could you not simply inline and then jump over the .@ part instead? So something like 2j@.~'0-\a*+. That would save 2 bytes. Commented Oct 12, 2020 at 2:17
• @Gegell That works indeed, thanks a lot!
– ovs
Commented Oct 12, 2020 at 7:44
• Is there a tool to generate an animation like that?
– att
Commented Oct 12, 2020 at 7:47
• @att There is this interpreter that uses pygame to draw the code and the stack on the screen. This doesn't create an animation though so you have to do some screen recording. For this animation I used my own tool, which is currently quite platform-specific, but uses the more complete PyFunge interpreter for executing the code.
– ovs
Commented Oct 12, 2020 at 7:54

# 05AB1E, 6 bytes

Ç48-Tβ


Explanation:

Ç       # Convert the (implicit) input-string to a list of codepoint integers
48-    # Subtract 48 from each value
Tβ  # Convert this from a base-10 list to a base-10 integer
# (after which it is output implicitly as result)


# Rust, 42 bytes

|s|s.chars().fold(0,|n,x|n*10+x as i32-48)


Try it online!

Takes input as an &str and outputs the number based on utf-8 codepoints.

# Ruby, 38 bytes

->s{s.bytes.inject(0){|a,b|b-48+a*10}}


35 bytes with the new Ruby 2.7 syntax:

->s{s.bytes.inject(0){_2-48+_1*10}}


Try it online!

# ><>, 15 bytes

0l1=?na*{68*-+!


Try it Online!

Explanation

0             !         Accumulator initialisation, skipped on subsequent loops
l1=?na*                Print-and-terminate condition
a*                Decimal shift
{               Next character of input

• But some things smell fishy... (there are errors) Commented Oct 13, 2020 at 12:41
• @SunnyMoon A common way of terminating the program. a* does double duty here. Commented Oct 13, 2020 at 13:59

# Clojure, 41 bytes

#(reduce(fn[x y](+(* 10 x)-48(int y)))0%)


Try it online!

Or alternatively, for the same byte count with a different order of full and shorthand function notation:

(fn[x](reduce #(+(* 10%)-48(int %2))0 x))


Try it online!

# Whitespace, 88 bytes

[S S S N
_Push_0][N
S S N
_Create_Label_LOOP][S S S N
_Push_0][S N
S _Duplicate_top][T N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve][S N
S _Duplicate][S S S T   N
_Push_1][T  S S T   _Subtract][N
T   S S N
_If_0_Jump_to_Label_EXIT][S S S T   T   S S S S N
_Push_48][T S S T   _Subtract][S N
T   _Swap_top_two][S S S T  S T S N
_Push_10][T S S N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_EXIT][S N
N
S T _Print_as_integer]


Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Since Whitespace inputs one character at a time, the input should contain a trailing ␁ (character with codepoint 1) so it knows when to stop reading characters and the input is done.

Try it online (with raw spaces, tabs and new-lines only).

Explanation in pseudo-code:

Integer result = 0
Start LOOP:
Integer input = STDIN as character
If(input - 1 == 0):
input = input - 48
result = result * 10
result = result + input
Go to the next iteration of LOOP

Label EXIT:
Print result as integer to STDOUT


Example run: input = "Hi!"

Command     Explanation                Stack           Heap     STDIN  STDOUT  STDERR

SSSN        Push 0                     [0]
NSSN        Create Label LOOP          [0]
SSSN       Push 0                     [0,0]
SNS        Duplicate top (0)          [0,0,0]
TNTS       Read STDIN as character    [0,0]           {0:72}   H
TTT        Retrieve at address (0)    [0,72]          {0:72}
SNS        Duplicate top (72)         [0,72,72]       {0:72}
SSSTN      Push 1                     [0,72,72,1]     {0:72}
TSST       Subtract top two (72-1)    [0,72,71]       {0:72}
SSSTTSSSN  Push 48                    [0,72,48]       {0:72}
TSST       Subtract top two (72-48)   [0,24]          {0:72}
SNT        Swap top two               [24,0]          {0:72}
SSSTSTSN   Push 10                    [24,0,10]       {0:72}
TSSN       Multiply top two (0*10)    [24,0]          {0:72}
TSSS       Add top two (24+0)         [24]            {0:72}

SSSN       Push 0                     [24,0]          {0:72}
SNS        Duplicate top (0)          [24,0,0]        {0:72}
TNTS       Read STDIN as character    [24,0]          {0:105}  i
TTT        Retrieve at address (0)    [24,105]        {0:105}
SNS        Duplicate top (105)        [24,105,105]    {0:105}
SSSTN      Push 1                     [24,105,105,1]  {0:105}
TSST       Subtract top two (105-1)   [24,105,104]    {0:105}
SSSTTSSSN  Push 48                    [24,105,48]     {0:105}
TSST       Subtract top two (106-48)  [24,57]         {0:105}
SNT        Swap top two               [57,24]         {0:105}
SSSTSTSN   Push 10                    [57,24,10]      {0:105}
TSSN       Multiply top two (24*10)   [57,240]        {0:105}
TSSS       Add top two (57+240)       [297]           {0:105}

SSSN       Push 0                     [297,0]         {0:105}
SNS        Duplicate top (0)          [297,0,0]       {0:105}
TNTS       Read STDIN as character    [297,0]         {0:33}   !
TTT        Retrieve at address (0)    [297,33]        {0:33}
SNS        Duplicate top (33)         [297,33,33]     {0:33}
SSSTN      Push 1                     [297,33,33,1]   {0:33}
TSST       Subtract top two (33-1)    [297,33,32]     {0:33}
SSSTTSSSN  Push 48                    [297,33,48]     {0:33}
TSST       Subtract top two (33-48)   [297,-15]       {0:33}
SNT        Swap top two               [-15,297]       {0:33}
SSSTSTSN   Push 10                    [-15,297,10]    {0:33}
TSSN       Multiply top two (297*10)  [-15,2970]      {0:33}
TSSS       Add top two (57+240)       [2955]          {0:33}

SSSN       Push 0                     [2955,0]        {0:33}
SNS        Duplicate top (0)          [2955,0,0]      {0:33}
TNTS       Read STDIN as character    [2955,0]        {0:1}    ␁
TTT        Retrieve at address (297)  [2955,1]        {0:1}
SNS        Duplicate top (1)          [2955,1,1]      {0:1}
SSSTN      Push 1                     [2955,1,1,1]    {0:1}
TSST       Subtract top two (1-1)     [2955,1,0]      {0:1}