有人说NSString -> NSData 很简单啊 [str dataUsingEncoding:NSUTF8StringEncoding] 就解决了
如果这么简单,那么就没有必要写这篇简书了!
举个🌰 ,“0013A00D”->0x0013A00D
下面进入正题
– (NSData *)transForm:(NSString *)str{
//拥有一个可变字符串
NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:str.length];
//使用循环,将转好的格式依次放入MutableData中
for (NSInteger i = 0; i < [str length]; i += 2) {
//定义int类型 存放数据
unsigned int anInt;
//获取相应的String
NSString *hexCharStr = [str substringWithRange:range];
//调用NSScanner将string-int-data
NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
[scanner scanHexInt:&anInt];
NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
[hexData appendData:entity];
range.location += range.length;
range.length = 2;
}
return hexData;
}