snippetjavaMinor
Convert decimal to binary and vice-versa in Java
Viewed 0 times
viceconvertdecimalversajavabinaryand
Problem
I'm trying to learn Java, so I'm doing a few exercises from a programmer project idea book. This exercise requires that the program be able to convert a decimal number to binary and vice versa, like so:
Here's the code I came up with:
`import java.util.Scanner;
public class BinaryToDecimalAndBackConverter{
static String convertDecimalToBinary(String decimal){
int integer = Integer.valueOf(decimal);
String result = new String();
while(integer > 0){
result+=String.valueOf(integer%2);
integer/=2;
}
result = new StringBuffer(result).reverse().toString();
return result;
}
static int convertBinaryToDecimal(String binary){
int result = 0;
for(int reverseCounter = 0; reverseCounter
Please enter the binary/decimal number to convert:9783569
100101010100100100010001
Please enter the binary/decimal number to convert:100101010100100100010001
9783569
Here's the code I came up with:
`import java.util.Scanner;
public class BinaryToDecimalAndBackConverter{
static String convertDecimalToBinary(String decimal){
int integer = Integer.valueOf(decimal);
String result = new String();
while(integer > 0){
result+=String.valueOf(integer%2);
integer/=2;
}
result = new StringBuffer(result).reverse().toString();
return result;
}
static int convertBinaryToDecimal(String binary){
int result = 0;
for(int reverseCounter = 0; reverseCounter
Solution
The best way to do it:
By the way your code looks good except for at least two issues:
I would correct it in this way:
static String convertDecimalToBinary(String decimal) {
return Integer.toString(Integer.parseInt(decimal, 10), 2);
}
static int convertBinaryToDecimal(String binary) {
return Integer.parseInt(binary, 2);
}By the way your code looks good except for at least two issues:
- Don't work with negative numbers
- The method
isDecimalOrBinaryis ambiguous: what's the result of the100input? It'sbinaryof course, but if i meant one hundred? I suggest to delegate the user to specify it.
I would correct it in this way:
import java.util.Scanner;
public class BinaryToDecimalAndBackConverter {
static String convertDecimalToBinary(String decimal) {
final boolean isNegative = decimal.startsWith("-");
if (isNegative) {
decimal = decimal.substring(1);
}
int integer = Integer.valueOf(decimal);
String result = new String();
while (integer > 0) {
result += String.valueOf(integer % 2);
integer /= 2;
}
// use StringBuilder instead of StringBuffer, we are sure about
// exclusive access, no need to use a thread safe class
final StringBuilder resultBuilder = new StringBuilder(result);
if (isNegative) {
resultBuilder.append("-");
}
return resultBuilder.reverse().toString();
}
static int convertBinaryToDecimal(String binary) {
final boolean isNegative = binary.startsWith("-");
if (isNegative) {
binary = binary.substring(1);
}
int result = 0;
for (int reverseCounter = 0; reverseCounter < binary.length(); reverseCounter++) {
final char currentChar = binary.charAt(binary.length() - reverseCounter - 1);
final int numericValue = Character.getNumericValue(currentChar);
result += Math.pow(2, reverseCounter) * numericValue;
// System.out.println(Math.pow(2, reverseCounter) *
// Character.getNumericValue(binary.charAt(binary.length() -
// reverseCounter - 1)) + " reverseCounter " + reverseCounter);
}
if (isNegative) {
result = -result;
}
return result;
}
public static void main(String[] args) {
final Scanner inputScanner = new Scanner(System.in);
System.out.print("Please enter the binary/decimal number to convert:");
// expected input: NUM D|B
final String[] splittedInput = inputScanner.nextLine().split(" ");
if (splittedInput.length != 2) {
// don't forget to close the Scanner
inputScanner.close();
throw new IllegalArgumentException("Wrong input format: expected NUM D|B");
}
final String input = splittedInput[0];
switch (splittedInput[1]) {
case "d":
case "D":
System.out.println(convertDecimalToBinary(input));
break;
case "b":
case "B":
System.out.println(convertBinaryToDecimal(input));
break;
default:
// don't forget to close the Scanner
inputScanner.close();
throw new IllegalArgumentException(
"Wrong input format: expected NUM D|B, the second argument was not D nor B");
}
// don't forget to close the Scanner
inputScanner.close();
}
}Code Snippets
static String convertDecimalToBinary(String decimal) {
return Integer.toString(Integer.parseInt(decimal, 10), 2);
}
static int convertBinaryToDecimal(String binary) {
return Integer.parseInt(binary, 2);
}import java.util.Scanner;
public class BinaryToDecimalAndBackConverter {
static String convertDecimalToBinary(String decimal) {
final boolean isNegative = decimal.startsWith("-");
if (isNegative) {
decimal = decimal.substring(1);
}
int integer = Integer.valueOf(decimal);
String result = new String();
while (integer > 0) {
result += String.valueOf(integer % 2);
integer /= 2;
}
// use StringBuilder instead of StringBuffer, we are sure about
// exclusive access, no need to use a thread safe class
final StringBuilder resultBuilder = new StringBuilder(result);
if (isNegative) {
resultBuilder.append("-");
}
return resultBuilder.reverse().toString();
}
static int convertBinaryToDecimal(String binary) {
final boolean isNegative = binary.startsWith("-");
if (isNegative) {
binary = binary.substring(1);
}
int result = 0;
for (int reverseCounter = 0; reverseCounter < binary.length(); reverseCounter++) {
final char currentChar = binary.charAt(binary.length() - reverseCounter - 1);
final int numericValue = Character.getNumericValue(currentChar);
result += Math.pow(2, reverseCounter) * numericValue;
// System.out.println(Math.pow(2, reverseCounter) *
// Character.getNumericValue(binary.charAt(binary.length() -
// reverseCounter - 1)) + " reverseCounter " + reverseCounter);
}
if (isNegative) {
result = -result;
}
return result;
}
public static void main(String[] args) {
final Scanner inputScanner = new Scanner(System.in);
System.out.print("Please enter the binary/decimal number to convert:");
// expected input: NUM D|B
final String[] splittedInput = inputScanner.nextLine().split(" ");
if (splittedInput.length != 2) {
// don't forget to close the Scanner
inputScanner.close();
throw new IllegalArgumentException("Wrong input format: expected NUM D|B");
}
final String input = splittedInput[0];
switch (splittedInput[1]) {
case "d":
case "D":
System.out.println(convertDecimalToBinary(input));
break;
case "b":
case "B":
System.out.println(convertBinaryToDecimal(input));
break;
default:
// don't forget to close the Scanner
inputScanner.close();
throw new IllegalArgumentException(
"Wrong input format: expected NUM D|B, the second argument was not D nor B");
}
// don't forget to close the Scanner
inputScanner.close();
}
}Context
StackExchange Code Review Q#117167, answer score: 2
Revisions (0)
No revisions yet.