Skip to content

Add a bitwise conversion for DecimalToBinary. #380

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 19, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 48 additions & 23 deletions Conversions/DecimalToBinary.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,52 @@
* @author Unknown
*
*/
class DecimalToBinary
{
/**
* Main Method
*
* @param args Command Line Arguments
*/
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n,k,s=0,c=0,d;
System.out.print("Decimal number: ");
n=sc.nextInt();
k=n;
while(k!=0)
{
d=k%2;
s=s+d*(int)Math.pow(10,c++);
k/=2;
}//converting decimal to binary
System.out.println("Binary equivalent:"+s);
sc.close();
}
class DecimalToBinary {

/**
* Main Method
*
* @param args Command Line Arguments
*/
public static void main(String args[]) {
conventionalConversion();
bitwiseConversion();
}

/**
* This method converts a decimal number
* to a binary number using a conventional
* algorithm.
*/
public static void conventionalConversion() {
int n, b = 0, c = 0, d;
Scanner input = new Scanner(System.in);
System.out.printf("Conventional conversion.\n\tEnter the decimal number: ");
n = input.nextInt();
while (n != 0) {
d = n % 2;
b = b + d * (int) Math.pow(10, c++);
n /= 2;
} //converting decimal to binary
System.out.println("\tBinary number: " + b);
}

/**
* This method converts a decimal number
* to a binary number using a bitwise
* algorithm
*/
public static void bitwiseConversion() {
int n, b = 0, c = 0, d;
Scanner input = new Scanner(System.in);
System.out.printf("Bitwise conversion.\n\tEnter the decimal number: ");
n = input.nextInt();
while (n != 0) {
d = (n & 1);
b += d * (int) Math.pow(10, c++);
n >>= 1;
}
System.out.println("\tBinary number: " + b);
}

}