Skip to content

Instantly share code, notes, and snippets.

@ani03sha
Created March 17, 2019 06:30
Show Gist options
  • Save ani03sha/6c159fa20f8054ab7e793d0385978db0 to your computer and use it in GitHub Desktop.
Save ani03sha/6c159fa20f8054ab7e793d0385978db0 to your computer and use it in GitHub Desktop.
This gist demonstrates the methods for binary to decimal and decimal to binary conversion
package org.redquark.help.march19;
import java.util.Scanner;
/**
*
* @author Anirudh Sharma
*
*/
public class BinaryDecimalConversion {
public static void main(String[] args) {
// Create a scanner instance to get the input from the user
Scanner input = new Scanner(System.in);
// Get the binary number which needs to be converted into decimal
int binary = Integer.parseInt(input.next());
// Converting binary to decimal
System.out.println(binary + " ==> " + binaryToDecimal(binary));
// Get the decimal which needs to be converted into binary
int decimal = input.nextInt();
// Converting decimal to binary
decimalToBinary(decimal);
// Closing the Scanner to avoid memory leaks
input.close();
}
/**
* This method accepts binary argument and convert it into decimal
* @param binary
* @return decimal equivalent
*/
private static int binaryToDecimal(int binary) {
// Decimal equivalent
int decimal = 0;
// The place determines the exponent of 2
int place = 0;
// Divide the number by 10 until true
while (true) {
if (binary == 0) {
break;
} else {
int temp = binary % 10;
// Decimal should be added to its previous value and the place raised to the power 2
decimal += temp * Math.pow(2, place);
// Move to more significant digit
binary = binary / 10;
// Increment place for more significant digit
place++;
}
}
return decimal;
}
/**
* This method converts decimal input to its binary equivalent
* @param decimal
*/
private static void decimalToBinary(int decimal) {
// Array that will store the binary digits
int[] binary = new int[40];
// This variable will store the index of each binary digit
int index = 0;
// Divide the decimal by 2 until possible
while (decimal > 0) {
// Remainders after dividing the decimal by 2 will be stored
binary[index++] = decimal % 2;
// Move forward
decimal = decimal / 2;
}
// Prints the binary digits in the reverse order
for (int i = index - 1; i >= 0; i--) {
System.out.print(binary[i]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment