1

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?

Nick
  • 155
  • 1
  • 8
  • I think you'll need to be more specific, you're unlikely to get a complete answer to your homework assignment from this website. – SoapBox May 16 '10 at 19:09
  • "Assembly" isn't a well-defined language. Which chipset? x86? – user168715 May 16 '10 at 19:11
  • Figure out how you'd do it by hand. Post that, and we'll help with representing that in ASM. – tpdi May 16 '10 at 19:13
  • @SoapBox Sorry but i'm not expecting a complete answer. I just need some ideas. @user168715 I'm sorry, i had x86 in the tags but i could only submit 6 tags max. It's there now – Nick May 16 '10 at 19:32

2 Answers2

3

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?

user168715
  • 5,469
  • 1
  • 31
  • 42
  • you mean answer[] is a string saved as BYTE that holds the characters of the output number? – Nick May 16 '10 at 19:42
  • The pseudocode saves each digit as an integer, but it's trivial to convert to a character (just add 0x30). – user168715 May 16 '10 at 20:00
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.

Mark Synowiec
  • 5,385
  • 1
  • 22
  • 18