美文网首页
iOS 16进制字符串转化为NSData类型

iOS 16进制字符串转化为NSData类型

作者: 呆呆滴木木菇凉 | 来源:发表于2018-10-12 17:20 被阅读0次
    - (NSData *)convertHexStrToData:(NSString *)str {
        if (!str || [str length] == 0) {
            return nil;
        }
        
        NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
        NSRange range;
        if ([str length] % 2 == 0) {
            range = NSMakeRange(0, 2);
        } else {
            range = NSMakeRange(0, 1);
        }
        for (NSInteger i = range.location; i < [str length]; i += 2) {
            unsigned int anInt;
            NSString *hexCharStr = [str substringWithRange:range];
            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;
        }
        
        NSLog(@"hexdata: %@", hexData);
        return hexData;
    }
    

    相关文章

      网友评论

          本文标题:iOS 16进制字符串转化为NSData类型

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