Objective-C NSString类型转成NSData类型

有人说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;

}

    原文作者:Bubble___x_x
    原文地址: https://www.jianshu.com/p/4313645f80b4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞