Sikau

Assembly language · Day 8 · about 40 min

Project: Printing numbers

Turn a number into decimal digits yourself — what printf does under the hood.

No print-int allowed

Real systems don't have a magic "print integer" call: something has to turn 1234 into the characters '1', '2', '3', '4'. Do it yourself: take digits off the end with remu 10, turn each into a character (+48), fill a buffer backwards, and print the string.

Digits come out backwards

It's a small routine, but writing it yourself removes one more piece of magic from how computers show you anything.

Taking n remu 10 gives the last digit, and n divu 10 removes it. Repeat until n is zero and you get the digits from right to left: 1234 gives 4, 3, 2, 1. Writing them into the buffer from its end towards the front puts them in reading order without a separate reverse step.

# n = 1234, buffer ends at buf + 11 with a 0 byte
# remu → 4, store '4' at buf+10, n = 123
# remu → 3, store '3' at buf+9,  n = 12
# remu → 2, store '2' at buf+8,  n = 1
# remu → 1, store '1' at buf+7,  n = 0 → stop
# print the string starting at buf+7: "1234"

The rest of this lesson

  • Edge casesexplain
  • What printf really doesexplain
  • One digitorder
  • Test input to expected outputmatch
  • print_uintchallenge
  • Badge quizquiz
  • Unit 2 completerecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 12 lessons of Assembly language