Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public static int binaryToDecimal(String binary) {
int decimal = 0;
int position = 0;
for (int x = binary.length() - 1; x >= 0; x--) {
// Saber si es 1 o 0; primero asumimos que es 1 y abajo comprobamos
short digit = 1;
if (binary.charAt(x) == '0') {
digit = 0;
}
double multiplier = Math.pow(2, position);
decimal += digit * multiplier;
position++;
}
return decimal;
}
public static String decimalToBinary(int decimal) {
if (decimal <= 0) {
return "0";
}
String binary = "";
while (decimal > 0) {
short remainder = (short) (decimal % 2);
decimal = decimal / 2;
binary = String.valueOf(remainder) + binary;
}
return binary;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment