HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Binary string to decimal conversion

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
conversionstringbinarydecimal

Problem

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 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;
}

@Tes

Solution

Usability

The Binary class has two kinds of usages:

  • Create an instance from a binary string, to get the decimal value later



  • A utility class with a utility method to convert a binary string to decimal value



Having two usages is confusing.
In general, an API that lets you accomplish the same thing in multiple ways raises questions like "which way is better",
which is not a very productive discussion.
Just provide one way, and there will be less questions asked, less confusion.

In this particular example,
it might make sense to move the converter logic to a BinaryUtils utility class.
If you still want a class that contains a binary string and decimal value,
then you can keep the Binary class for that purpose.

Pre-calculate when it makes sense

Getters should not calculation. When I see a method named "getSomething",
I assume it simply returns the value of a field (or sometimes a defensive copy).
But in this class, it calculates the decimal value.
Every time it's called, again and again.
Since the method always returns the same value,
it would be better to calculate that value once,
at construction time.
And that way, the getter will naturally really return just a simple field value.

Avoid negation in names

Negation as the "Not" in charIsNotBinary may lead to double-negation in code like if (!charIsNotBinary(...)) { ... }, which can be confusing.
It's better to rewrite as isBinary, and use ! where you need to negate it.

Using `` operators is also slightly odd, feels kind of overkill for a range of size 2.
This way seems simpler and more natural:

private static boolean isBinary(char ch) {
    return ch == '0' || ch == '1';
  }

Code Snippets

private static boolean isBinary(char ch) {
    return ch == '0' || ch == '1';
  }

Context

StackExchange Code Review Q#128875, answer score: 4

Revisions (0)

No revisions yet.