MCPcopy Create free account
hub / github.com/TheAlgorithms/Java / AnytoAny

Class AnytoAny

src/main/java/com/thealgorithms/conversions/AnytoAny.java:9–68  ·  view source on GitHub ↗

A utility class for converting numbers from any base to any other base. This class provides a method to convert a source number from a given base to a destination number in another base. Valid bases range from 2 to 10.

Source from the content-addressed store, hash-verified

7 * to a destination number in another base. Valid bases range from 2 to 10.
8 */
9public final class AnytoAny {
10 private AnytoAny() {
11 }
12
13 /**
14 * Converts a number from a source base to a destination base.
15 *
16 * @param sourceNumber The number in the source base (as an integer).
17 * @param sourceBase The base of the source number (between 2 and 10).
18 * @param destBase The base to which the number should be converted (between 2 and 10).
19 * @throws IllegalArgumentException if the bases are not between 2 and 10.
20 * @return The converted number in the destination base (as an integer).
21 */
22 public static int convertBase(int sourceNumber, int sourceBase, int destBase) {
23 if (sourceBase < 2 || sourceBase > 10 || destBase < 2 || destBase > 10) {
24 throw new IllegalArgumentException("Bases must be between 2 and 10.");
25 }
26
27 int decimalValue = toDecimal(sourceNumber, sourceBase);
28 return fromDecimal(decimalValue, destBase);
29 }
30
31 /**
32 * Converts a number from a given base to its decimal representation (base 10).
33 *
34 * @param number The number in the original base.
35 * @param base The base of the given number.
36 * @return The decimal representation of the number.
37 */
38 private static int toDecimal(int number, int base) {
39 int decimalValue = 0;
40 int multiplier = 1;
41
42 while (number != 0) {
43 decimalValue += (number % 10) * multiplier;
44 multiplier *= base;
45 number /= 10;
46 }
47 return decimalValue;
48 }
49
50 /**
51 * Converts a decimal (base 10) number to a specified base.
52 *
53 * @param decimal The decimal number to convert.
54 * @param base The destination base for conversion.
55 * @return The number in the specified base.
56 */
57 private static int fromDecimal(int decimal, int base) {
58 int result = 0;
59 int multiplier = 1;
60
61 while (decimal != 0) {
62 result += (decimal % base) * multiplier;
63 multiplier *= 10;
64 decimal /= base;
65 }
66 return result;

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected