posprintf - a condensed version of sprintf for Thumb, esp. GBA


By Dan Posluns, released into the public domain.


This routine is unsafe, make sure the destination buffer is big enough to hold the output string!

Also, note that it functions slightly differently from sprintf in the C standard library.


import natu/[video, irq, bios, tte, posprintf]

let friends = 12
let maxFriends = 50

# write formatted text into a buffer
var buffer: array[100, char]
posprintf(addr buffer, "You found %d out of %d friends.", friends, maxFriends)

# draw the text on background 0
tte.initChr4c(bgnr = 0, initBgCnt(cbb = 0, sbb = 31))
tte.write(addr buffer)

# show background 0
dispcnt = initDispCnt(bg0 = true)

# wait forever:
while true:
proc posprintf(dest: cstring, src: cstring)
  • src must be a valid zero-terminated C string.

  • dest must point to a sufficiently large block of memory to contain the result string.

The following format specifiers are valid:


print a % symbol


print a string; parameter must point to a valid zero-terminated C string


print a 16-bit (short) integer; must be within -65,535 .. 65,535


print a 29-bit integer; approximate range -500,000,000 .. 500,000,000


print a hexadecimal number (lowercase digits)


print a hexadecimal number (uppercase digits)

The specifiers %d, %l, %x and %X may be modified as follows:

  • Digits 1 through 9 indicate number of leading spaces to print, eg.
    %5d would print the number 123 as "  123"
    %5d would print the number 123456 as "123456" (no leading spaces)
  • When above digit is prefixed with 0, leading zeros are printed instead of spaces
    %05d would print the number 123 as "00123"
    %04d would print the number 12345 as "12345" (no leading zeros)
  • Negative sign consumes a leading space, eg.
    %05d would print the number -123 as "-0123"
    (Hexadecimal numbers are considered unsigned)