Some of what I wrote here is for the non-Forth-literate, since it's not in the Forth sub-forum and the same method can be used without Forth.
Because of how/where >DIGIT gets used, there's no need to check to see if it's valid, regardless of the desired base. When turning a number into ASCII for human output, you divide it by the contents of variable BASE and take the remainder for each digit as you build the number right to left, repeatedly, until the input number is 0. The remainder will always be less than the base, so it is guaranteed to be valid, without error checking. The same routine works for any base you could ever want, and in fact BASE will sometimes change in the process, like when forming a time string where the minutes' and seconds' ones' place goes 0-9 but the tens' place only goes 0-5. You might also want to put in punctuation (using HOLD), like the ":" in the case of the time string (for example, 3:27:49.1), or the decimal point, comma, / (for dates), - (the minus sign at the left end), or other character.
What I have for >DIGIT in my '816 Forth is:
Code:
HEADER ">DIGIT", NOT_IMMEDIATE ; ( n -- ASCII_CHR ) ( b -- ASCII_CHR )
TO_DIGIT: PRIMITIVE ; Turn number (0-15) into ASCII character.
LDA 0,X ; We'll do it in 16-bit to avoid changing from
CMP #$A ; 16 to 8 and back. It's only meaningful for
BCC ja30 ; bytes though.
ADC #6 ; Add only 6, not 7, because C flag was set.
ja30: ADC #$30 ; Carry flag is always clear when getting here.
STA 0,X
GO_NEXT
;-------------------
For going the other direction, you do need to see if it's valid, as you're starting with ASCII. Take each digit, turn it into a number if possible, multiply the number you're building by the contents of BASE, and add the quantity specified by the new ASCII digit. Loop until you reach an ASCII value that's neither a valid digit in the chosen base nor a specified-valid character (like - . , / :). Mine uses CONVERT and NUMBER? which are not primitives. I'll add them later if someone wants them.
I highly recommend keeping it such that the BASE can be anything and is kept in BASE, and the same routines get used for all conversions regardless of base.