获取单个中文字符的机内码(GBK码)

/**
 获取单个中文字符的机内码(GBK码)
 
 @param string 单个中文字符
 @return 机内码
 */
+ (int)getGBKFromChinese:(NSString *)string{
    
    NSString *urlEncoded = (__bridge_transfer NSString *)
    CFURLCreateStringByAddingPercentEscapes(NULL,
                                            (__bridge CFStringRef)string,NULL,
                                            (CFStringRef)@"!*'\"();:@&=+$,?%#[]%",
                                            kCFStringEncodingGB_18030_2000);
    NSString *heigh1 = [urlEncoded substringWithRange:NSMakeRange(1, 1)];
    NSString *heigh2 = [urlEncoded substringWithRange:NSMakeRange(2, 1)];
    int heightValue = [self hexToInt:heigh1] * 16 + [self hexToInt:heigh2];
    
    NSString *low1 = [urlEncoded substringWithRange:NSMakeRange(4, 1)];
    NSString *low2 = [urlEncoded substringWithRange:NSMakeRange(5, 1)];
    int lowValue = [self hexToInt:low1] * 16 + [self hexToInt:low2];
    int result = heightValue * 256 + lowValue;
    return result;
}

/**
 将十六进制字符串转换为十进制数字
 ABCD -> 43981    A -> 10
 @param string 十六进制字符串
 @return 十进制数字
 */
+ (int)hexToInt:(NSString *)string{
    if (string.length > 1) {
        int lengh = (int)string.length;
        int result = 0;
        for (int i = 0; i < lengh; i++) {
            NSString *tagSting = [string substringWithRange:NSMakeRange(i, 1)];
            int tagValue = [self hexToInt:tagSting] * pow(16, lengh - i - 1);
            result += tagValue;
        }
        return result;
    }
    if ([string isEqualToString:@"0"]) {
        return 0;
    } else if ([string isEqualToString:@"1"]) {
        return 1;
    } else if ([string isEqualToString:@"2"]) {
        return 2;
    } else if ([string isEqualToString:@"3"]) {
        return 3;
    } else if ([string isEqualToString:@"4"]) {
        return 4;
    } else if ([string isEqualToString:@"5"]) {
        return 5;
    } else if ([string isEqualToString:@"6"]) {
        return 6;
    } else if ([string isEqualToString:@"7"]) {
        return 7;
    } else if ([string isEqualToString:@"8"]) {
        return 8;
    } else if ([string isEqualToString:@"9"]) {
        return 9;
    } else if ([string isEqualToString:@"A"]) {
        return 10;
    } else if ([string isEqualToString:@"B"]) {
        return 11;
    } else if ([string isEqualToString:@"C"]) {
        return 12;
    } else if ([string isEqualToString:@"D"]) {
        return 13;
    } else if ([string isEqualToString:@"E"]) {
        return 14;
    } else if ([string isEqualToString:@"F"]) {
        return 15;
    }
    return 0;
}

你可能感兴趣的:(获取单个中文字符的机内码(GBK码))