Created
August 21, 2020 18:56
-
-
Save parzibyte/9f64ead1e96b39f141f2882ab8d64312 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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