Mirror of CollapseOS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

116 lines
2.2KB

  1. ; *** Requirements ***
  2. ; stdioPutC
  3. ; divide
  4. ;
  5. ; Same as fmtDecimal, but DE is considered a signed number
  6. fmtDecimalS:
  7. bit 7, d
  8. jr z, fmtDecimal ; unset, not negative
  9. ; Invert DE. spit '-', unset bit, then call fmtDecimal
  10. push de
  11. ld a, '-'
  12. ld (hl), a
  13. inc hl
  14. ld a, d
  15. cpl
  16. ld d, a
  17. ld a, e
  18. cpl
  19. ld e, a
  20. inc de
  21. call fmtDecimal
  22. dec hl
  23. pop de
  24. ret
  25. ; Format the number in DE into the string at (HL) in a decimal form.
  26. ; Null-terminated. DE is considered an unsigned number.
  27. fmtDecimal:
  28. push ix
  29. push hl
  30. push de
  31. push af
  32. push hl \ pop ix
  33. ex de, hl ; orig number now in HL
  34. ld e, 0
  35. .loop1:
  36. call .div10
  37. push hl ; push remainder. --> lvl E
  38. inc e
  39. ld a, b ; result 0?
  40. or c
  41. push bc \ pop hl
  42. jr nz, .loop1 ; not zero, continue
  43. ; We now have C digits to print in the stack.
  44. ; Spit them!
  45. push ix \ pop hl ; restore orig HL.
  46. ld b, e
  47. .loop2:
  48. pop de ; <-- lvl E
  49. ld a, '0'
  50. add a, e
  51. ld (hl), a
  52. inc hl
  53. djnz .loop2
  54. ; null terminate
  55. xor a
  56. ld (hl), a
  57. pop af
  58. pop de
  59. pop hl
  60. pop ix
  61. ret
  62. .div10:
  63. push de
  64. ld de, 0x000a
  65. call divide
  66. pop de
  67. ret
  68. ; Format the lower nibble of A into a hex char and stores the result in A.
  69. fmtHex:
  70. ; The idea here is that there's 7 characters between '9' and 'A'
  71. ; in the ASCII table, and so we add 7 if the digit is >9.
  72. ; daa is designed for using Binary Coded Decimal format, where each
  73. ; nibble represents a single base 10 digit. If a nibble has a value >9,
  74. ; it adds 6 to that nibble, carrying to the next nibble and bringing the
  75. ; value back between 0-9. This gives us 6 of that 7 we needed to add, so
  76. ; then we just condtionally set the carry and add that carry, along with
  77. ; a number that maps 0 to '0'. We also need the upper nibble to be a
  78. ; set value, and have the N, C and H flags clear.
  79. or 0xf0
  80. daa ; now a =0x50 + the original value + 0x06 if >= 0xfa
  81. add a, 0xa0 ; cause a carry for the values that were >=0x0a
  82. adc a, 0x40
  83. ret
  84. ; Print the hex char in A as a pair of hex digits.
  85. printHex:
  86. push af
  87. ; let's start with the leftmost char
  88. rra \ rra \ rra \ rra
  89. call fmtHex
  90. call stdioPutC
  91. ; and now with the rightmost
  92. pop af \ push af
  93. call fmtHex
  94. call stdioPutC
  95. pop af
  96. ret
  97. ; Print the hex pair in HL
  98. printHexPair:
  99. push af
  100. ld a, h
  101. call printHex
  102. ld a, l
  103. call printHex
  104. pop af
  105. ret