2

I had an interview recently and discovered that I'd forgotten some of the basics. I've been playing around again and have written a function that will take a binary string (there is no validation yet) and returns the ascii representation of said string.

I'm looking for advice or tips on how it could be improved. I don't want to use any of the API functions, this is more of a playground scenario in which I might be able to learn something.

Thanks for any help.

Sample output:

01101000 01100101 01101100 01101100 01101111 
104
101
108
108
111
hello



public static String convertBinaryStringToString(String string){
    StringBuilder sb = new StringBuilder();
    char[] chars = string.replaceAll("\\s", "").toCharArray();
    int [] mapping = {1,2,4,8,16,32,64,128};

    for (int j = 0; j < chars.length; j+=8) {
        int idx = 0;
        int sum = 0;
        for (int i = 7; i>= 0; i--) {
            if (chars[i+j] == '1') {
                sum += mapping[idx];
            }
            idx++;
        }
        System.out.println(sum);//debug
        sb.append(Character.toChars(sum));
    }
    return sb.toString();
}
11
  • 2
    And you don't want to use Integer.parseInt("10001001",2); ? Commented Apr 30, 2015 at 11:58
  • 1
    I don't have enough experience here to say one way or the other (I'm not 100% sure how much code is required for CR)... but I think it would be okay to post in both places for now. My reasoning is that since you're looking to improve upon working code, CR should be fine. Commented Apr 30, 2015 at 11:58
  • 1
    @Trobbins, thanks, I'll post in the other site and remove one or the other once something happens. :) Commented Apr 30, 2015 at 11:59
  • 1
    Similar post [here][1] with multiple answers and approaches. [1]: stackoverflow.com/questions/4211705/binary-to-text-in-java Commented Apr 30, 2015 at 12:02
  • 1
    @SteveGreen "I don't wish to use API functions." Aren't you doing that with Character.toChars ? Commented Apr 30, 2015 at 12:10

2 Answers 2

3

You don't need an array with the powers of two - the computer already knows them and you can use 1<<k to get the k-th power of two. However you don't need that either. Here is a short function to parse int from a char array that is the binary representation of a number. With a little modification the code will work for any base up to 10.

public static int parseBinary(char[] chars) {
  int res = 0;
  for (int i = 0; i < s.length; ++i) {
    res *= 2;
    if (chars[i] == '1') {
      res += 1;
    }
  }
  return res;
}

Using this function you can simplify your code significantly.

Sign up to request clarification or add additional context in comments.

Comments

0

If you want a more java8-ish solution:

public static String convertBinaryStringToString(String string) {
    return stream(string.split("\\s+"))
            .mapToInt(s -> s.chars().reduce(0, (x, y) -> (char) (x * 2 + (y-'0'))))
            .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
            .toString();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.