0

I have binary string like this: String a = "100100". I need to have binary byte array: byte[] b = {1,0,0,1,0,0} for output.

This is my code:

    String a="100100";

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

But this approach is not working when i run it. Can any one give a correction? Thank you

2 Answers 2

0

byte[] is not initialized. So we need to initialize before we use it .

byte[] b = new byte[a.length()];

try this
0
0

You haven't assigned a value to your byte[] b, hence resulting in a NullPointerException, since you later reference it by index.

Try this instead:

String a="100100";

byte[] b = new byte[a.length()]; // here
for (int i = 0; i < a.length(); i++) {
    b[i]=a.charAt(i)=='1'? (byte) 1: (byte) 0;
}
System.out.println(Arrays.toString(b)); // easier print once finished

Output

[1, 0, 0, 1, 0, 0]
0

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.