Add a bitwise conversion for DecimalToBinary.
This commit is contained in:
parent
7320201a44
commit
80aa51daa2
@ -6,27 +6,52 @@ import java.util.Scanner;
|
|||||||
* @author Unknown
|
* @author Unknown
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
class DecimalToBinary
|
class DecimalToBinary {
|
||||||
{
|
|
||||||
/**
|
/**
|
||||||
* Main Method
|
* Main Method
|
||||||
*
|
*
|
||||||
* @param args Command Line Arguments
|
* @param args Command Line Arguments
|
||||||
*/
|
*/
|
||||||
public static void main(String args[])
|
public static void main(String args[]) {
|
||||||
{
|
conventionalConversion();
|
||||||
Scanner sc=new Scanner(System.in);
|
bitwiseConversion();
|
||||||
int n,k,s=0,c=0,d;
|
}
|
||||||
System.out.print("Decimal number: ");
|
|
||||||
n=sc.nextInt();
|
/**
|
||||||
k=n;
|
* This method converts a decimal number
|
||||||
while(k!=0)
|
* to a binary number using a conventional
|
||||||
{
|
* algorithm.
|
||||||
d=k%2;
|
*/
|
||||||
s=s+d*(int)Math.pow(10,c++);
|
public static void conventionalConversion() {
|
||||||
k/=2;
|
int n, b = 0, c = 0, d;
|
||||||
}//converting decimal to binary
|
Scanner input = new Scanner(System.in);
|
||||||
System.out.println("Binary equivalent:"+s);
|
System.out.printf("Conventional conversion.\n\tEnter the decimal number: ");
|
||||||
sc.close();
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user