将十六进制字符串转换成字节数组

NSString *str = @"AA21f0c1762a3abc299c013abe7dbcc50001DD"

将里面的字符转换到Byte数组中,如下

Byte buffer[] = { 0xAA, 0x21, 0xf0, 0xc1, 0x76, 0x2a, 0x3a, ... , 0x01, 0xDD }

@interface NSString (NSStringHexToBytes)

-(NSData*) hexToBytes ;

@end

@implementation NSString (NSStringHexToBytes)

-(NSData*) hexToBytes {

NSMutableData* data = [NSMutableDatadata];

int idx;

for (idx = 0; idx+2 <= self.length; idx+=2) {

NSRange range = NSMakeRange(idx, 2);

NSString* hexStr = [selfsubstringWithRange:range];

NSScanner* scanner = [NSScannerscannerWithString:hexStr];

unsignedint intValue;

[scanner scanHexInt:&intValue];

[data appendBytes:&intValue length:1];

}

return data;

}

@end

应用:

NSData *data = [str hexToBytes];

你可能感兴趣的:(将十六进制字符串转换成字节数组)