美文网首页iOS Developer
iOS数据转换面试题

iOS数据转换面试题

作者: 806349745123 | 来源:发表于2017-07-06 17:15 被阅读167次

    将一串表示16进制的字符串转换成NSData

    /**
     将16进制字符串转换成data值和字符串字符相等的NSData
     比如输入@"3e435fab9c34891f"
     输出的NSData的byte是3e435fab9c34891f
    
     @param hexString 16进制字符串
     @return 转换后NSData
     */
    static NSData* dataWithHexString(NSString *hexString) {
    hexString = [hexString stringByReplacingOccurrencesOfString:@" " withString:@""];
        // 将16进制数据转化成Byte 数组
        NSUInteger bytesCount = hexString.length / 2;
        Byte bytes[bytesCount];
        
        for(int i = 0; i < [hexString length]; i++)
        {
            int int_ch;  /// 两位16进制数转化后的10进制数
            
            unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
            int int_ch1;
            if(hex_char1 >= '0' && hex_char1 <='9')
                int_ch1 = (hex_char1 - '0') << 4;   //// 0 的Ascll - 48
            else if(hex_char1 >= 'A' && hex_char1 <='F')
                int_ch1 = (hex_char1 - 65 + 10) << 4; //// A 的Ascll - 65, 26个大写字母
            else
                int_ch1 = (hex_char1 - 97 + 10) << 4; //// a 的Ascll - 97, 26个小写字母
            i++;
            
            unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
            int int_ch2;
            if(hex_char2 >= '0' && hex_char2 <='9')
                int_ch2 = (hex_char2 - 48); //// 0 的Ascll - 48
            else if(hex_char1 >= 'A' && hex_char1 <='F')
                int_ch2 = (hex_char2 - 65) + 10; //// A 的Ascll - 65
            else
                int_ch2 = (hex_char2 - 97) + 10; //// a 的Ascll - 97
            
            int_ch = int_ch1 + int_ch2;
            NSLog(@"int_ch=%d",int_ch);
            bytes[i/2] = int_ch;  ///将转化后的数放入Byte数组里
        }
        NSData *newData = [[NSData alloc] initWithBytes:bytes length:bytesCount];
        NSLog(@"newData=%@",newData);
        return newData;
    }
    

    YYKit里面也有相应的处理方法

    + (NSData *)dataWithHexString:(NSString *)hexStr {
        hexStr = [hexStr stringByReplacingOccurrencesOfString:@" " withString:@""];
        hexStr = [hexStr lowercaseString];
        NSUInteger len = hexStr.length;
        if (!len) return nil;
        unichar *buf = malloc(sizeof(unichar) * len);
        if (!buf) return nil;
        [hexStr getCharacters:buf range:NSMakeRange(0, len)]; // 把char存入buf
        
        NSMutableData *result = [NSMutableData data];
        unsigned char bytes;
        char str[3] = { '\0', '\0', '\0' };
        int i;
        for (i = 0; i < len / 2; i++) {
            str[0] = buf[i * 2];// 高4位
            str[1] = buf[i * 2 + 1]; // 低4位
            bytes = strtol(str, NULL, 16); // 将串转换为长整数
            [result appendBytes:&bytes length:1];
        }
        free(buf);
        return result;
    }
    

    相关文章

      网友评论

        本文标题:iOS数据转换面试题

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