在我蓝牙开发的时候,我从通过蓝牙获得设备的16进制数据流时,发生了高位字节和低位字节互换的情况,导致我解析的unicode数据是乱码。
举例:
\u9065表示“遥”,但是因为数据传输时发生了高位和低位的转换,所以我收到的实际是\u6590,解码出来的文字变成了“斐”。
解决办法
//这是我获取的有效的数据流
NSString *dataString = @"6590dc8f2e006d007000330000000";
[self decodingHiloUnicodeData:dataString];
- (NSString *)decodingHiloUnicodeData:(NSString *)hexStr{
NSMutableArray * hexArray = [[NSMutableArray alloc] init];
//4位16进制数据表示一个字符,默认最后不满4位的16进制数据放一起
for (int i=0; i<ceil(hexStr.length/4.0); i++) {
NSString *subString;
if (i==ceil(hexStr.length/4.0)-1) {
subString = [hexStr substringFromIndex:i*4];
}
else{
subString = [hexStr substringWithRange:NSMakeRange(i*4, 4)];
}
[hexArray addObject:subString];
}
[hexArray enumerateObjectsUsingBlock:^(NSString * _Nonnull string, NSUInteger idx, BOOL * _Nonnull stop) {
//最后不满4位的不管
if (string.length==4) {
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (int i=0; i<string.length/2; i++) {
NSString *subString = [string substringWithRange:NSMakeRange(i*2, 2)];
[tempArray addObject:subString];
}
//一个字符的两个字节位置互换
[tempArray exchangeObjectAtIndex:0 withObjectAtIndex:1];
NSString *tempString = [NSString stringWithFormat:@"%@%@",tempArray[0],tempArray[1]];
[hexArray replaceObjectAtIndex:idx withObject:tempString];
}
}];
NSString *hexString = @"" ;
for (NSString *string in hexArray) {
hexString = [hexString stringByAppendingString:string];
}
NSData *mydata = [self hexToBytes:hexString];
NSString *finalString = [[NSString alloc] initWithData:mydata encoding:NSUnicodeStringEncoding];
return finalString;
}
/**
* 将16进制的字符串转化为data数据
*
* @param str @"90658fdc002e006d0070003300000"
*
* @return <90658fdc 002e006d 00700033 0000>
*/
-(NSData *)hexToBytes:(NSString *)str{
NSMutableData* data = [NSMutableData data];
int idx;
for (idx = 0; idx+2 <= str.length; idx+=2) {
NSRange range = NSMakeRange(idx, 2);
NSString* hexStr = [str substringWithRange:range];
NSScanner* scanner = [NSScanner scannerWithString:hexStr];
unsigned int intValue;
[scanner scanHexInt:&intValue];
[data appendBytes:&intValue length:1];
}
return data;
}
输出:
遥远.mp3