Write a function that returns a decimal number from a binary string. The functio
ID: 3817985 • Letter: W
Question
Write a function that returns a decimal number from a binary string. The function header is as follows int bin2 Dec (const strings binarystring) For example, binarystring 10001 is 17 (1 x 2^4 0 x 2^3 0 x 2^2 0 x 2 + 1 x 2^0 = 17) So, bin2 Dec ("10001") returns 17. Write a function that parses a decimal number into a binary number as a string. The function header is as follows: string dec2Bin (int value) For example, dec2Bin (17) returns string "10001" Write a test program that prompts the user to enter a binary or decimal number and display its equivalent value in decimal or binary.Explanation / Answer
BinaryConversion.java
package binary;
/**
*
* @author Naresh Kumar
*
*/
public class BinaryConversion {
/**
* This method is responsible to convert binary to decimal value
* @param binaryNumber
* @return
*/
public static int bin2Dec(String binaryNumber) {
int decimalValue= 0;
int power = 0;
int binaryValue = Integer.parseInt(binaryNumber);
while (true) {
if (binaryValue == 0) {
break;
} else {
int tmp = binaryValue % 10;
decimalValue += tmp * Math.pow(2, power);
binaryValue = binaryValue / 10;
power++;
}
}
return decimalValue;
}
/**
* This method is responsible to convert decimal to binary value
* @param binaryNumber
* @return
*/
public static String dec2Bin(int binaryNumber) {
return Integer.toBinaryString(binaryNumber);
}
}
Test.java
package binary;
import java.util.Scanner;
/**
*
* @author Naresh Kumar
*
*/
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter decimal value :");
String input = scan.nextLine();
System.out.println(BinaryConversion.bin2Dec(input));
System.out.println("Enter binary value :");
int binaryInput = scan.nextInt();
System.out.println(BinaryConversion.dec2Bin(binaryInput));
scan.close();
}
}
Output
Enter decimal value :
10001
17
Enter binary value :
17
10001
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.