+ 1
Help in coding
I need your help with the base converter I am realizing. The program needs to realize that digits in higher bases over 9 from A to F are numbers and I need to be able to make calculations with them. Like C/3== 12/3== 4 I'd like to have ideas, how i can realize that? https://code.sololearn.com/c1q6reRziohA/?ref=app
2 ответов
+ 4
Read the numb as a string. Use parseInt to convert any base to integer. Do your calculations as integers. Convert to string with toString.
int from=in.nextInt();
String numb=in.next();
int to=in.nextInt();
int value=Integer.parseInt(numb, from);
// regular integer math as needed
String result = Integer.toString(value, to);
+ 2
I assume you're trying to build a converter from scratch for practice, rather than using an existing library..
I'd suggest building this up gradually, so focus on say base 16, make that work and then extend to other bases gradually.
Perhaps make a Map from String to Integer with the letter values you need (so map.get("C") will return 12). You might need one to go from numbers to letters too (a BiMap from the Guava library is a two way map, though I don't know if this works on playground).
Remember the important thing (e.g. in hexadecimal) is what remainder do you have on dividing 16? e.g. 24 % 16 = 8 so my hex unit will be 8. Now divide by 16 (which is integer division) I get 1. 1 % 16 = 1 so I have hex 18 = dec 24. If the remainder is 12, (or in fact, greater than 9) use your map. Think about what end condition you want to look for. Definitely use a String to build up your answer (perhaps even StringBuilder? concatenation would be fine though)
Once you have a working function, then start to think how you can generalize the parameters to allow different bases.
Hope this helps and feel free to update us with your progress :)
Edit: Reading your code you have lots of these elements anyway, so the maps and stuff should help tidy it