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

前端 未结 2 1859
一生所求
一生所求 2021-01-25 16:56

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 ente

相关标签:
2条回答
  • 2021-01-25 17:24

    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?

    0 讨论(0)
  • 2021-01-25 17:29

    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.

    0 讨论(0)
提交回复
热议问题