-2

I'm writing a program that allows conversion between base 10, base 2, and base 8. I decided to make it so that it can from any base to any base by using the method where you divide the number being converted by the base it's being converted to. The problem is that if I have say 15 in base 2 1111 and I'd like to convert it to base 10 so I make java divide 1111 by 1010 it's not going to know that I want base 2 division and it will treat it as standard base 10 division.

Is there a way to do arithmetic in different bases in java?

Inzinity
  • 41
  • 6

1 Answers1

2

Arithmetic is arithmetic, regardless of base. The actual value "1010" in base 2 is exactly the same as the value "10" in base 10, and division between them works exactly alike. Bases are just a matter of representation.

I can go ahead and tell you that if you're trying to represent 10 in base 2 like int x = 1010, you're doing it wrong.

Store and operate on values internally; you don't need to worry about how the computer is representing them to itself. Just put wrapper functions around where those values are shown to the user - so, a set of functions with headers like:

int fromBaseTen(String numberWrittenInBaseTen){...}
String toBaseTen(int number){...}
int fromBaseTwo(String numberWrittenInBaseTwo){...}
String toBaseTwo(int number){...}
Edward Peters
  • 3,623
  • 2
  • 16
  • 39