当前位置 : 主页 > 手机开发 > ios >

iOS获取字符串string的异或值

来源:互联网 收集:自由互联 发布时间:2021-06-11
#import Foundation/Foundation.hNS_ASSUME_NONNULL_BEGIN@interface HKXORManager : NSObject+ (HKXORManager *)shareManager;/** * 计算异或值 * @param string 需要异或的字符串 * @return 获取异或后的字符串 */- (NSString *)stri
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface HKXORManager : NSObject

+ (HKXORManager *)shareManager;
/**
 * 计算异或值
 * @param string 需要异或的字符串
 * @return 获取异或后的字符串
 */
- (NSString *)stringXOR:(NSString *)string;

@end

NS_ASSUME_NONNULL_END

  

#import "HKXORManager.h"

@implementation HKXORManager

+ (HKXORManager *)shareManager {
    static HKXORManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[HKXORManager alloc] init];
    });
    return instance;
}

- (NSString *)stringXOR:(NSString *)string {
    if (string.length%2) {
        string = [NSString stringWithFormat:@"0%@", string];
    }
    NSString *code = @"00";
    for (int i=0; i<string.length; i=i+2) {
        NSString *subString = [string substringWithRange:NSMakeRange(i, 2)];
        code = [self pinxCreator:code withPinv:subString];
    }
    return code;
}

- (NSString *)pinxCreator:(NSString *)pan withPinv:(NSString *)pinv {
    if (pan.length != pinv.length) {
        return nil;
    }
    const char *panchar = [pan UTF8String];
    const char *pinvchar = [pinv UTF8String];
    NSString *temp = [[NSString alloc] init];
    for (int i = 0; i < pan.length; i++) {
        int panValue = [self charToint:panchar[i]];
        int pinvValue = [self charToint:pinvchar[i]];
        temp = [temp stringByAppendingString:[NSString stringWithFormat:@"%X",panValue^pinvValue]];
    }
    return temp;
}

- (int)charToint:(char)tempChar {
    if (tempChar >= 0 && tempChar <=9) {
        return tempChar - 0;
    }
    else if (tempChar >= A && tempChar <= F) {
        return tempChar - A + 10;
    }
    return 0;
}

@end
网友评论