如何有效二进制字符串转换为二进制字节数组在Java中? [英] How to convert efficiently binary string to binary byte array in Java?
问题描述
作为输入我有二进制串字符串A =100110
。作为输出我需要的二进制字节数组字节[] B = {1,0,0,1,1,0}
。
现在我使用
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;我++){
B〔Ⅰ〕=的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<a.length; i++) {
b[i]= a.charAt(i)=='1' ? (byte)1 : (byte)0;
}
原因你的做法是比较慢的是,每次调用串
产生一个新的字符串
对象,有资格垃圾收集尽快 parseByte
与它完成。
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.
这篇关于如何有效二进制字符串转换为二进制字节数组在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!