2

As an input I have binary string String a = "100110". As output I need to have binary byte array byte[] b = {1,0,0,1,1,0}. For now I'm using

for (int i=0; i<a.length; i++) { b[i]= Byte.parseByte(a.substring(i, i+1)); }

But this approach is too slow. Can any one give a better suggestion? Thank you

3

3 Answers 3

6

You can do it without making objects for substrings, like this:

for (int i=0; i<a.length; i++) {
    b[i]= a.charAt(i)=='1' ? (byte)1 : (byte)0;
}

The reason your approach is slower is that each call to substring produces a new String object, which becomes eligible for garbage collection as soon as parseByte is done with it.

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

Comments

5

Assuming the input is valid...

    byte[] b = new byte[a.length()];
    for (int i = 0; i < b.length; i++) {
        b[i] = (byte) (a.charAt(i) - '0');
    }

Comments

1

Makes an int[] instead of byte[] but I hope for points for elegance:

    int[] a = "100110"
            // Turn it into a stream.
            .chars()
            // Make '0'/'1' into 0/1
            .map(c -> c - '0')
            // Roll it into an array.
            .toArray();

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.