 # Binary / Hex - Challenge in JAVA

Hey there folks!

Again I am presenting you my solution in Java for this challenge!

Please be aware that the String reverser (the for-loop) in the hex()-function is not ideal for every solution, I am sorry. But maybe soon enough I will find the best way to do this!

Edit 02.07.2022 : Hmm maybe with arrays…

``````public class Main {

static String binary(int num) {

int remainder;
int counter = num;
String binary = "", outcome = "";
char reverser;

while(true) {

if(counter != 0) {
remainder = counter%2;
counter /= 2;
binary += remainder;
//				System.out.println(counter + " R" + remainder);
continue;

} else {
break;
}
}

// String reverser
for (int i = 0; i < binary.length(); i++) {
reverser = binary.charAt(i);
outcome = reverser + outcome;
}
return outcome;
}

static String hex(int num) {

int remainder;
int counter = num;
String hex = "", outcome = "";
char reverser;

while(true) {

if(counter != 0) {

remainder = counter%16;
counter /= 16;

if(remainder == 10) {
hex += "A";
} else if(remainder == 11) {
hex += "B";
} else if(remainder == 12) {
hex += "C";
} else if(remainder == 13) {
hex += "D";
} else if(remainder == 14) {
hex += "E";
} else if(remainder == 15) {
hex += "F";
} else {
hex += remainder;
}
continue;

} else {
break;
}
}

// String reverser
for (int i = 0; i < hex.length(); i++) {  // ATTETION! This does not work, if the outcome is e.g. C10 -> 01C (not good)
reverser = hex.charAt(i);
outcome = reverser + outcome;
}
return outcome;
}

public static void main(String[] args) {

int toConvertNumber = 173;

System.out.println("BIN 173:\t" + binary(toConvertNumber));
System.out.println("HEX 173:\t" + hex(toConvertNumber));
}
}
``````

OUTPUT Have a great day <3

That looks really good! Good to see how you apply this with JAVA!

Kind regards, Lisa