1

I need help with a program in C# that has to convert any number (whether integer or long decimal) to any base (within reason).

The program has several text boxes (it's a win form) all starting blank. When the user adds numbers (possibly with a decimal) to one of the boxes all of the update. The default boxes are bases 2,8,10,16, and the last box has a sub box to enter a base of your choice (for if the user wanted to for example convert a number base 16 to base 7.

I do not know of any works other than Convert that has the ability to base convert.

If you do not know how to do this, at least explaining how one would do this manually would be awesome! What is 64.96(base ten) in octal?

This is a personal project. I set challenges and then set out to complete a program...

Thanks in advance for any help!!

Edit: How would I do this in C#? int BaseX is the base I need to get to. int preBaseX is the base I'm coming from. decimal outputNumber is the number I'm searching for. decimal inputNumber is where we are starting with. (it can be 650.3112 or whatever)

Masoniik
  • 13
  • 4
  • 2
    Have you tried googleing for an existing class that does this conversion? I found this with a quick search: http://stackoverflow.com/questions/923771/quickest-way-to-convert-a-base-10-number-to-any-base-in-net Also this: http://www.codeproject.com/Articles/16872/Number-base-conversion-class-in-C –  Nov 04 '13 at 03:22

1 Answers1

2

To convert 64.96 to octal, first decide how many places past the "octal point" you want show. Let's say you want 3. Then multiply your number by 8^3 or 512.

64.96 * 512 = 33259.52

Discard the fractional part. This, by the way is how far off of 64.96 your representation will be. Your answer will be 0.52/512 = 0.001015625 too small.

Now, for the conversion. Repeatedly divide your number (33259) by 8, keeping track of the remainders:

33259 / 8 = 4157 remainder 3
4157  / 8 = 519  remainder 5
519   / 8 = 64   remainder 7
64    / 8 = 8    remainder 0
8     / 8 = 1    remainder 0
1     / 8 = 0    remainder 1

Now, take your remainders in reverse order and insert the "octal point" 3 from the end:

100.753

vacawama
  • 150,663
  • 30
  • 266
  • 294
  • This is really helpful! Quick question, does the "octal point" go three from the front or three from the back of the number? (you showed 100.753, do you count from the front or back?) – Masoniik Nov 05 '13 at 04:09
  • 3 from the back. I said "end" which I now realize is ambiguous, but I meant "end" as in start/end. – vacawama Nov 05 '13 at 14:04
  • This works for other bases as well, of course. For base 16, remainders 10 through 15 would be represented by the hexadecimal digits "A" through "F" respectively. – vacawama Nov 05 '13 at 14:06