Search

mercredi 8 février 2017

Print code as decimal number

Context

Memory cells contain values, that can be easily displayed (using .).
However, this displays the value as an ASCII character. In order to display the integer value (in base 10), we need to
  • Do successive euclidean divisions on the value and its successive quotients, to get digits (successive reminders)
  • As remainder can be 0, store remainder + 1
  • Add 47 to each digit (ASCII code for 0, stored as 1 according to line above) and display the char

Initial state

  • Memory: 0, A, 0, ...
  • Cursor: second cell
  • Input: any

Process

  • While current cell is not null
    • Divide by ten (see Euclidean division article)
    • Move remainder+1 to current cell, quotient to next cell
    • Move cursor to quotient
  • Memory state: 0, a, b, c, d, ..., 0, with a, b, c, d, ... digits of A, in reverse order
  • Move to left (first digit of A)
  • While current cell is not null
    • Add 48 (6*8 is faster)
    • Remove 1 and print char
    • Clear
    • Move right

Code

[
  >>>>++++++++++<<<<[->+>>+>-[<-]<[->>+<<<<[->>>+<<<]>]<<]
  (divide by ten)

  >+[-<+>]>>>[-]>[-<<<<+>>>>]<<<<
  (move results to the right place)
]
<[>++++++[<++++++++>-]<-.[-]<]
(display result)

Code (minified)

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

Final state

  • Memory: 0
  • Cursor: first cell
  • Input: any
  • Output: A, written in base 10

Aucun commentaire:

Enregistrer un commentaire