16进制字符串与NSData,数字,二进制字符串之间的转化

2019-01-14  本文已影响0人  落雨轩_在路上

16进制字符串转化为数字:

+ (NSInteger)numberWithHexString:(NSString*)hexString{

    const char *hexChar = [hexString cStringUsingEncoding:NSUTF8StringEncoding];

    int hexNumber;

    sscanf(hexChar,"%x", &hexNumber);

    return  (NSInteger)hexNumber;

}

十六进制字符串转换为二进制字符串:

+ (NSString*)getBinaryByHex:(NSString*)hex {

    NSMutableDictionary *hexDic = [[NSMutableDictionary alloc] initWithCapacity:16];

    [hexDicsetObject:@"0000"forKey:@"0"];

    [hexDicsetObject:@"0001"forKey:@"1"];

    [hexDicsetObject:@"0010"forKey:@"2"];

    [hexDicsetObject:@"0011"forKey:@"3"];

    [hexDicsetObject:@"0100"forKey:@"4"];

    [hexDicsetObject:@"0101"forKey:@"5"];

    [hexDicsetObject:@"0110"forKey:@"6"];

    [hexDicsetObject:@"0111"forKey:@"7"];

    [hexDicsetObject:@"1000"forKey:@"8"];

    [hexDicsetObject:@"1001"forKey:@"9"];

    [hexDicsetObject:@"1010"forKey:@"A"];

    [hexDicsetObject:@"1011"forKey:@"B"];

    [hexDicsetObject:@"1100"forKey:@"C"];

    [hexDicsetObject:@"1101"forKey:@"D"];

    [hexDicsetObject:@"1110"forKey:@"E"];

    [hexDicsetObject:@"1111"forKey:@"F"];

    NSString*binary =@"";

    for(inti=0; i<[hexlength]; i++) {

        NSString *key = [hex substringWithRange:NSMakeRange(i, 1)];

        NSString*value = [hexDicobjectForKey:key.uppercaseString];

        if(value) {

            binary = [binarystringByAppendingString:value];

        }

    }

    return binary;

}

16进制字符串转化为NSData:

-(NSData*) hexToBytes:(NSString*)str {

    NSMutableData* data = [NSMutableData data];

    intidx;

    for(idx =0; idx+2<= str.length; idx+=2) {

        NSRangerange =NSMakeRange(idx,2);

        NSString* hexStr = [strsubstringWithRange:range];

        NSScanner* scanner = [NSScannerscannerWithString:hexStr];

        unsignedintintValue;

        [scannerscanHexInt:&intValue];

        [dataappendBytes:&intValuelength:1];

    }

    returndata;

}

上一篇 下一篇

猜你喜欢

热点阅读