2019-05-09 19:32:54 +08:00
|
|
|
package Conversions;
|
|
|
|
|
2017-04-18 22:57:17 +08:00
|
|
|
import java.util.Scanner;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* This class converts a Decimal number to a Binary number
|
|
|
|
*
|
2019-12-11 12:35:54 +08:00
|
|
|
*
|
2017-04-18 22:57:17 +08:00
|
|
|
*/
|
2018-02-19 08:56:49 +08:00
|
|
|
class DecimalToBinary {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Main Method
|
2019-05-09 19:32:54 +08:00
|
|
|
*
|
2018-02-19 08:56:49 +08:00
|
|
|
* @param args Command Line Arguments
|
|
|
|
*/
|
|
|
|
public static void main(String args[]) {
|
|
|
|
conventionalConversion();
|
|
|
|
bitwiseConversion();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2019-05-09 19:32:54 +08:00
|
|
|
* This method converts a decimal number
|
2018-02-19 08:56:49 +08:00
|
|
|
* 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);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2019-05-09 19:32:54 +08:00
|
|
|
* This method converts a decimal number
|
2018-02-19 08:56:49 +08:00
|
|
|
* 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);
|
2020-01-29 00:34:52 +08:00
|
|
|
input.close();
|
2018-02-19 08:56:49 +08:00
|
|
|
}
|
|
|
|
|
2017-04-18 22:57:17 +08:00
|
|
|
}
|