美文网首页
16进制字符串与NSData,数字,二进制字符串之间的转化

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

作者: 落雨轩_在路上 | 来源:发表于2019-01-14 17:03 被阅读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;

}

相关文章

网友评论

      本文标题:16进制字符串与NSData,数字,二进制字符串之间的转化

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