当前位置:   article > 正文

java 二进制数组,如何有效二进制字符串转换为二进制字节数组在Java中?

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

b[i]= Byte.parseByte(a.substring(i, i+1));

}

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

解决方案

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

for (int i=0; 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.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/618042
推荐阅读
相关标签
  

闽ICP备14008679号