Is there a way to convert a fixed size byte array to a String without iterating over the byte array to find where the String ends? The problem I'm having is that not all of the bytes in the byte array are characters. I'm padding the end of the array with 0
. If I use new String(byte[])
, it interprets the 0
s as part of the string. Is there a certain character I can pad the byte[] with and not have it interpret it as part of the String?
是否有一种方法可以将一个固定大小的字节数组转换成一个字符串,而不需要遍历字节数组以查找字符串的结尾?我的问题是字节数组中不是所有的字节都是字符。我用0填充数组的末尾。如果我使用新的字符串(byte[]),它将0解释为字符串的一部分。是否有某个字符我可以用[]填充而不让它将其解释为字符串的一部分?
2 个解决方案
#1
3
No, since all byte values are valid characters in a string. You must keep track of the count of valid bytes, and use the byte[], int, int
version of the constructor.
不,因为所有字节值都是字符串中的有效字符。您必须跟踪有效字节的计数,并使用构造函数的字节[],int, int版本。
If you don't want to keep track of the count manually (perhaps because you are building the byte array piecemeal), consider using a ByteArrayOutputStream
.
如果您不想手工跟踪计数(可能是因为您正在构建字节数组片段),可以考虑使用ByteArrayOutputStream。
#2
2
There's a String constructor that takes a byte[]
, a begin offset, and a length as arguments -- just use that to tell the String which bytes to include.
有一个字符串构造函数,它接受一个字节[]、一个开始偏移量和一个长度作为参数—只是使用它来告诉字符串包含哪些字节。
#1
3
No, since all byte values are valid characters in a string. You must keep track of the count of valid bytes, and use the byte[], int, int
version of the constructor.
不,因为所有字节值都是字符串中的有效字符。您必须跟踪有效字节的计数,并使用构造函数的字节[],int, int版本。
If you don't want to keep track of the count manually (perhaps because you are building the byte array piecemeal), consider using a ByteArrayOutputStream
.
如果您不想手工跟踪计数(可能是因为您正在构建字节数组片段),可以考虑使用ByteArrayOutputStream。
#2
2
There's a String constructor that takes a byte[]
, a begin offset, and a length as arguments -- just use that to tell the String which bytes to include.
有一个字符串构造函数,它接受一个字节[]、一个开始偏移量和一个长度作为参数—只是使用它来告诉字符串包含哪些字节。