How can I convert a number in a string to any base in assembly?

无人久伴 提交于 2019-12-20 04:16:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!