Skip to content

Commit 80aa51d

Browse files
committed
Add a bitwise conversion for DecimalToBinary.
1 parent 7320201 commit 80aa51d

File tree

1 file changed

+48
-23
lines changed

1 file changed

+48
-23
lines changed

Conversions/DecimalToBinary.java

+48-23
Original file line numberDiff line numberDiff line change
@@ -6,27 +6,52 @@
66
* @author Unknown
77
*
88
*/
9-
class DecimalToBinary
10-
{
11-
/**
12-
* Main Method
13-
*
14-
* @param args Command Line Arguments
15-
*/
16-
public static void main(String args[])
17-
{
18-
Scanner sc=new Scanner(System.in);
19-
int n,k,s=0,c=0,d;
20-
System.out.print("Decimal number: ");
21-
n=sc.nextInt();
22-
k=n;
23-
while(k!=0)
24-
{
25-
d=k%2;
26-
s=s+d*(int)Math.pow(10,c++);
27-
k/=2;
28-
}//converting decimal to binary
29-
System.out.println("Binary equivalent:"+s);
30-
sc.close();
31-
}
9+
class DecimalToBinary {
10+
11+
/**
12+
* Main Method
13+
*
14+
* @param args Command Line Arguments
15+
*/
16+
public static void main(String args[]) {
17+
conventionalConversion();
18+
bitwiseConversion();
19+
}
20+
21+
/**
22+
* This method converts a decimal number
23+
* to a binary number using a conventional
24+
* algorithm.
25+
*/
26+
public static void conventionalConversion() {
27+
int n, b = 0, c = 0, d;
28+
Scanner input = new Scanner(System.in);
29+
System.out.printf("Conventional conversion.\n\tEnter the decimal number: ");
30+
n = input.nextInt();
31+
while (n != 0) {
32+
d = n % 2;
33+
b = b + d * (int) Math.pow(10, c++);
34+
n /= 2;
35+
} //converting decimal to binary
36+
System.out.println("\tBinary number: " + b);
37+
}
38+
39+
/**
40+
* This method converts a decimal number
41+
* to a binary number using a bitwise
42+
* algorithm
43+
*/
44+
public static void bitwiseConversion() {
45+
int n, b = 0, c = 0, d;
46+
Scanner input = new Scanner(System.in);
47+
System.out.printf("Bitwise conversion.\n\tEnter the decimal number: ");
48+
n = input.nextInt();
49+
while (n != 0) {
50+
d = (n & 1);
51+
b += d * (int) Math.pow(10, c++);
52+
n >>= 1;
53+
}
54+
System.out.println("\tBinary number: " + b);
55+
}
56+
3257
}

0 commit comments

Comments
 (0)