【发布时间】:2011-12-21 21:11:43
【问题描述】:
我从套接字接收到一个字节数组中的字符串,如下所示:
[128,5,6,3,45,0,0,0,0,0]
网络协议给出的大小是字符串的总长度(包括零)所以,在我的示例 10 中。
如果我只是这样做:
String myString = new String(myBuffer);
我在字符串的末尾有 5 个不正确的字符。转换似乎没有检测到字符串字符 (0) 的结尾。
为了获得正确的大小和正确的字符串,我这样做:
int sizeLabelTmp = 0;
//Iterate over the 10 bit to get the real size of the string
for(int j = 0; j<(sizeLabel); j++) {
byte charac = datasRec[j];
if(charac == 0)
break;
sizeLabelTmp ++;
}
// Create a temp byte array to make a correct conversion
byte[] label = new byte[sizeLabelTmp];
for(int j = 0; j<(sizeLabelTmp); j++) {
label[j] = datasRec[j];
}
String myString = new String(label);
有没有更好的方法来处理这个问题?
谢谢
【问题讨论】:
标签: java string bytearray type-conversion