1. Ask for input
Your goal here is to get a series of characters, these can be taken together as a whole string or one by one. If you take a whole string then you have to read it char by char, if you take one char at a time you are already done.
2. Convert numerical digits to digits
The chars you read are glyphs, symbols. Symbols in computer are represented (as everything else) with numbers. The way this mapping is done is your (charset) encoding. Without entering the vast realm of encoding you can rely on the fact that the glyphs for the decimal digits are encoded with the same numbers in the majority of western encoding, in particular you can assume ASCII encoding.
If you look at an ASCII table you see this
Character 0 1 2 3 4 5 6 7 8 9
Encoding 30h 31h 32h 33h 34h 35h 36h 37h 38h 39h
So if the user input 1234 you have these bytes in the string 31h 32h 33h 34h
.
Your goal is to convert from the encoding to the digit, for example the char '4' has encoding 34h
and you want to transform this into the value 4h
.
For base from 2 to 36 this can be done with basic arithmetic, more fancy bases may need look up tables.
Don't forget to validate the input! Check the string for valid characters!
3. Compute the number from the digits
Now you have a sequence of digits, let's call them dn, ..., d3, d2, d1, d0
where dn
is the first digit the user inputted and d0
the last one.
You want to create a number from this digits. You know that a number like 1234
actually means 1*10^3 + 2*10^2 + 3*10^1 + 4
.
So what you have to do is simply:
dn*10^n + ... + d3*10^3 + d2*10^2 + d1*10^1 + d0
(that explains my choice of subscripts)
Considering that n
is varying (min is 1 max is 5 for 16 bit numbers) you can simplify this computation by accumulating the partial result.
This means that you have a partial result temp
initially 0. Each time you have a new digit di
you perform
tmp = tmp*10 + di
Convince yourself that this effectively compute the sum above. This method brings for free the nice feature that you compute the low 16 bit of the number which usually is a graceful degradation for numbers that can't fit a WORD.
4. Pseudo algorithm
n = 0;
t = 0;
while (1)
{
c = get_char_from_input();
if (end_of_input(c) || max_digits_read(n))
break;
d = get_digit_from_char(c);
t = t * 10 + d;
n = n + 1;
}
return t;
Up to you the task to develop an efficient assembly version.