iOS HexString转换为NSData
即 与NSData的description方法的相反
- (NSData *)dataWithHexString:(NSString *)hexString {
NSString *newStr = [hexString stringByReplacingOccurrencesOfString:@" " withString:@""]; //去掉空格
NSString *replaceString = [newStr substringWithRange:NSMakeRange(1, newStr.length-2)]; //去掉<>符号
const char *hexChar = [replaceString UTF8String]; //转换为 char 字符串
Byte *bt = malloc(sizeof(Byte)*(replaceString.length/2)); // 开辟空间 用来存放 转换后的byte
char tmpChar[3] = {'\0','\0','\0'};
int btIndex = 0;
for (int i=0; i<replaceString.length; i += 2) {
tmpChar[0] = hexChar[i];
tmpChar[1] = hexChar[i+1];
bt[btIndex] = strtoul(tmpChar, NULL, 16); // 将 hexstring 转换为 byte 的c方法 16 为16进制
btIndex ++;
}
NSData *data = [NSData dataWithBytes:bt length:btIndex]; //创建 nsdata 对象
free(bt); //释放空间
return data;
}
这里核心转换代码用到了 c String库里的 unsigned long strtoul(const char *, char **, int);
完成转换