问题
How can I convert a number contained in a string from any base to any other base?
Bases can be anything i.e.: 2, 16, 10, 4, 8, 9.
I'm expecting the user to enter the base number. The user will enter the output base (the base to be converted to). The user will enter the number he wants to convert.
Pre thoughts: I will save the input base and the output base in variables. Then I'll save the number he enters in a string (because he could enter any kind of number (hex, binary, base-5..).
I'm just trying to figure out how to convert that string to a number so i can convert it to the output base.
Any ideas?
回答1:
To convert from a string to an integer, you'll need to take a look at an ASCII table.
iterate through each character in your string until you hit the end, and based off of what the character is and which range it's in: '0' to '9', 'a' to 'f', 'A' to 'F', you'll need to subtract the value of the bottom character in it's range and add any appropriate amount. then add that to an accumulator value and you should be set to go. i guess you'll also need to check for any values that hint at what base the value is in (for instance, i'd expect hex values to be prefixed by "0x").
So for instance, if you see a '1', you'll need to subtract off '0'. if you see an 'a', you'll need to subtract off 'a' and add 0x0a.
回答2:
The general algorithm for changing a number n to base b goes something like:
i = 0
while(n != 0)
answer[i] = n mod b
n /= b
i++
(Note that answer[0] holds the least significant digit of the answer.) Does this make sense? Which part of this pseudocode are you having trouble implementing?
来源:https://stackoverflow.com/questions/2845082/how-can-i-convert-a-number-in-a-string-to-any-base-in-assembly