Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created August 21, 2020 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/9f64ead1e96b39f141f2882ab8d64312 to your computer and use it in GitHub Desktop.
Save parzibyte/9f64ead1e96b39f141f2882ab8d64312 to your computer and use it in GitHub Desktop.
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