截取字符串末尾结束符。和硬件通讯时,往往接收到的数据带有字符串结束符0x00,如果不截取掉,JSON解析不了。下面提供截取的方法,将NSData的byte取出,循环查找末尾是否是0x00,是则截取掉
+ (NSData *)trimData:(NSData *)data {
NSMutableData *msgData = data.mutableCopy;
if (msgData.length >= 1) {
BOOL index = YES;
while (index) {
NSData *trimData = [msgData subdataWithRange:NSMakeRange(msgData.length-1, 1)];
Byte lastByte[1];
[trimData getBytes:lastByte range:NSMakeRange(0, 1)];
if (lastByte[0] == 0x00) {
[msgData replaceBytesInRange:NSMakeRange(msgData.length-1, 1) withBytes:NULL length:0];
index = YES;
} else {
index = NO;
}
}
}
return msgData;
}