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();
}
null
  • 3,469
  • 7
  • 41
  • 90
  • Someone else may correct me, but I think you have enough code to post here: http://codereview.stackexchange.com/ – CubeJockey Apr 30 '15 at 11:54
  • @Trobbins - would you like me to move the post, are you able to? If not, is the 'way' to delete this one and paste as a question on the code review site? – null Apr 30 '15 at 11:55
  • 2
    And you don't want to use Integer.parseInt("10001001",2); ? – Veselin Davidov Apr 30 '15 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. – CubeJockey Apr 30 '15 at 11:58
  • @VeselinDavidov, no, it's a exercise to simply see if I could. I was asked to reveres a string and parse an int as well as others in this interview, I was successful but it still made me very aware that I had forgotten many things :) – null Apr 30 '15 at 11:59
  • 1
    @Trobbins, thanks, I'll post in the other site and remove one or the other once something happens. :) – null Apr 30 '15 at 11:59
  • 1
    Similar post [here][1] with multiple answers and approaches. [1]: http://stackoverflow.com/questions/4211705/binary-to-text-in-java – daxeh Apr 30 '15 at 12:02
  • @AdrianTeh, thanks, I've visited that page before, I don't wish to use API functions. – null Apr 30 '15 at 12:04
  • 1
    @SteveGreen "I don't wish to use API functions." Aren't you doing that with `Character.toChars` ? – MadConan Apr 30 '15 at 12:10
  • @MadConan, would you believe me if I said I was now 'googling' for an alternative way? Have you anything else that might be productive or useful? – null Apr 30 '15 at 12:11
  • @SteveGreen I do believe you, I don't have an alternative. Since this is an exercise, you'll basically have to duplicate the code in `Character.toChars`. You could take your own shot at it first or look at the source now. – MadConan Apr 30 '15 at 12:14

2 Answers2

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.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
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();
}
Juan Lopes
  • 10,143
  • 2
  • 25
  • 44