美文网首页iOS知识集合
将十六进制字符串转换成字节数组

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

作者: iOS祎 | 来源:发表于2017-07-07 16:12 被阅读10次

    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];

    相关文章

      网友评论

        本文标题:将十六进制字符串转换成字节数组

        本文链接:https://www.haomeiwen.com/subject/wmfrhxtx.html