I begin by creating a variable for the current base and words to set this to specific values quickly.
Next, a string constant with the symbols for each digit. Note that I'm only going to support uppercase for hexadecimal.
So conversion to a numeric value is pretty easy. The basic idea here is:
• set a variable to hold the numeric value to zero (as a stating point)
• check to see if the first character is - for negative, set a modifier
• for each character in the string:
• convert to a numeric value (in this case, it's the index in the
DIGITS string) • Multiply the last value of the number accumulator by the base
• Add the converted value
• Store the result in the number accumulator
• Multiply the final number by the modifier
Going the other way, back to a string, follows a similar process.
• Take a value
• Divide by Base
• Convert result to character and append to a buffer
• If remainder is not zero, repeat
• If number is negative, append the '-' symbol to the buffer
• Reverse the buffer contents to return a string in the correct order
The n:to-string-with-base returns a representation of binary numbers, but not the actual bitwise representation. The next word takes care of this.