Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert efficiently binary string to binary byte array in Java?

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

like image 810
Sparrow_ua Avatar asked Apr 14 '26 04:04

Sparrow_ua


1 Answers

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.

like image 91
Sergey Kalinichenko Avatar answered Apr 16 '26 17:04

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!