Code patternsInput and outputRead a decimal number

Read a decimal number

Reads digits such as 173 and puts the number they spell in a cell.

Watch it run

The form “A line of digits” works on 3 cells, named “number”, “letter” and “scratch”. Press Play, drag the step slider forwards and back, or change the number typed with the slider:

The figure needs JavaScript. The program below is the result for the example values.

The digits arrive first to last. For every new digit: multiply what we have by 10, and add the digit. 1, then 17, then 173.

A digit arrives as a letter code, 48 more than its value. So 48 is taken off first.

Multiplying by 10 is the pattern multiply by a constant: a flat loop, one optimised step.

The code

This is the program the figure ran. It is brainfuck as it stands: copy it, or open it in the playground, where you can change it:

>,----------[>++++++[-<------>]<--<[->>++++++++++<<]>>[-<<+>>]<[-<+>],----------]<
Open in the playground82 characters

What it needs

Common mistakes
  • Feeding it anything but digits. Both forms treat every letter as a digit: "a" counts as 49.
  • Typing 300 on 8-bit cells and expecting 300. The cell holds 300 − 256 = 44.

What it costs

A plain step is one command. An optimised step is one step of an interpreter that folds runs of the same command and flat loops. Choose the values and watch the two bars; What costs what explains how cost is counted:

The figure needs JavaScript. The table below has the measured steps.

Cost as a formula, and measured
Table 1. The cost as a function of the values. Exact formulas are checked on every case they run.
FormPlain stepsOptimised steps
A line of digitsgrows with the number4 + 9 per digit
The form by Urban Müllergrows with the number16 + 19 per digit
Table 2. Measured when this page was written.
FormValuesBitsCharactersPlain stepsOptimised steps
A line of digitsn = 088210413
A line of digitsn = 788213913
A line of digitsn = 1738821,88731
The form by Urban Müllern = 173; ends with = a newline8941,97773

Other forms

The form by Urban Müller

Stops at a newline or at the end of the input. Layout: number, flag, letter, scratch.

[-]>[-]+[[-]>[-],[+[-----------[>[-]++++++[<------>-]<--<<[->>++++++++++<<]>>[-<<+>>]<+>]]]<]<
Open in the playground94 characters
Run this form step by step

The form “The form by Urban Müller” works on 4 cells, named “number”, “flag”, “letter” and “scratch”. Press Play, drag the step slider forwards and back, or change the number typed with the slider and edit the choice of ends with:

The figure needs JavaScript. The program below is the result for the example values.

Where it is used

Sources

Every program on this page was run on many inputs, in plain and in optimised mode, and compared with JavaScript. The explanations are written for this page.