// 十六进制转换成字符串
+(NSString*)dataToHexString:(NSData*)data {
if (data == nil) {
return @"";
}
Byte *dateByte = (Byte *)[data bytes];
NSString *hexStr=@"";
for(int i=0;i<[data length];i++) {
NSString *newHexStr = [NSString stringWithFormat:@"%x",dateByte[i]&0xff]; ///16进制数
if([newHexStr length]==1)
hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
else
hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
}
return hexStr;
}
//字符串转换十六进制 比如 FF ->0XFF
-(NSData*)convert:(NSString*)str{
const char* cs = str.UTF8String;
int count = (int)strlen(cs);
int8_t bytes[count / 2];
for(int i = 0; i<count; i+=2){
char c1 = *(cs + i);
char c2 = *(cs + i + 1);
if(C2I(c1) >= 0 && C2I(c2) >= 0){
bytes[i / 2] = C2I(c1) * 16 + C2I(c2);
}else{
return nil;
}
}
return [NSData dataWithBytes:bytes length:count /2];
}