Problem Statement:
Write a program that will convert a binary number, represented as a string (e.g. '101010'), to its decimal equivalent using first principles
Implement binary to decimal conversion. Given a binary input string, your program should produce a decimal output. The program should handle invalid inputs.
Code:
public class Binary {
private final String binaryString;
public Binary(String binaryString) {
this.binaryString = binaryString;
}
public int getDecimal() {
return toDecimal(binaryString);
}
public static int toDecimal(String str) {
int decimal = 0;
int base0 = (int)'0';
char ch;
for (int i = 0; i < str.length(); i++) {
ch = str.charAt(i);
if (charIsNotBinary(ch)) {
return 0;
}
decimal = decimal * 2 + ((int)str.charAt(i) - base0);
}
return decimal;
}
private static boolean charIsNotBinary(char ch) {
return '1' < ch || ch < '0';
}
}
Test Suite:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
@RunWith(Parameterized.class)
public class BinaryTest {
private String input;
private int expectedOutput;
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{"1", 1},
{"10", 2},
{"11", 3},
{"100", 4},
{"1001", 9},
{"11010", 26},
{"10001101000", 1128},
{"2", 0},
{"5", 0},
{"9", 0},
{"134678", 0},
{"abc10z", 0},
{"011", 3}
});
}
public BinaryTest(String input, int expectedOutput) {
this.input = input;
this.expectedOutput = expectedOutput;
}
@Test
public void test() {
Binary binary = new Binary(input);
assertEquals(expectedOutput, binary.getDecimal());
}
}
Reference:
Integer.parseInt(..., 2)
but want to do it yourself :). – Tunaki May 20 at 19:38