16进制字符串转data
-(NSData*)data_With_HexString:(NSString*)hexString
{
// hexString的长度应为偶数
if([hexStringlength] %2!=0)
returnnil;
NSUIntegerlen = [hexStringlength];
NSMutableData*retData = [[NSMutableDataalloc]init];
constchar*ch = [[hexStringdataUsingEncoding:NSASCIIStringEncoding]bytes];
for(inti=0; i
intheight=0;
if(ch[i]>='0'&& ch[i]<='9')
height = ch[i] -'0';
elseif(ch[i]>='A'&& ch[i]<='F')
height = ch[i] -'A'+10;
elseif(ch[i]>='a'&& ch[i]<='f')
height = ch[i] -'a'+10;
else
//错误数据
returnnil;
intlow=0;
if(ch[i+1]>='0'&& ch[i+1]<='9')
low = ch[i+1] -'0';
elseif(ch[i+1]>='A'&& ch[i+1]<='F')
low = ch[i+1] -'A'+10;
elseif(ch[i+1]>='a'&& ch[i+1]<='f')
low = ch[i+1] -'a'+10;
else
//错误数据
returnnil;
intbyteValue = height*16+ low;
[retDataappendBytes:&byteValuelength:1];
}
returnretData;
}
NSdata转16进制串
-(NSString*)convertDataToHexStrBLE:(NSData*)data {
if(!data || [datalength] ==0)
{
returnnil;
}
NSMutableString*string = [[NSMutableStringalloc]initWithCapacity:[datalength]];
[dataenumerateByteRangesUsingBlock:^(constvoid*bytes,NSRangebyteRange,BOOL*stop) {
unsignedchar*dataBytes = (unsignedchar*)bytes;
for(NSIntegeri =0; i < byteRange.length; i++)
{
NSString*hexStr = [NSStringstringWithFormat:@"%x", (dataBytes[i]) &0xff];
if([hexStrlength] ==2) {
[stringappendString:hexStr];
}else
{
[stringappendFormat:@"0%@", hexStr];
}
}
}];
returnstring;
}