Objective C 十六进制 十进制互转

十六进制转十进制:

NSString *hexStr = @"0xff";
UInt64 mac1 =  strtoul([hexStr UTF8String], 0, 16);
NSLog(@"%llu",mac1);
NSLog(@"十六进制转十进制 --->%lu",strtoul(hexStr.UTF8String, 0, 16));

如果有溢出的话,使用scanner:

NSString *hexStr1 = @"0x00000000027743330000000000714C9C";
unsigned long long result = 0;
NSScanner *scanner = [NSScanner scannerWithString:hexStr1];
[scanner scanHexLongLong:&result];
NSLog(@"%llu",result);

十六进制转NSString

 NSString * str = @"68656C6C6F";
    NSMutableString * newString = [[NSMutableString alloc] init] ;
    int i = 0;
    while (i < [str length])
    {
        NSString * hexChar = [str substringWithRange: NSMakeRange(i, 2)];
        int value = 0;
        sscanf([hexChar cStringUsingEncoding:NSASCIIStringEncoding], "%x", &value);
        [newString appendFormat:@"%c", (char)value];
        i+=2;
    }
    NSLog(@"new str :%@",newString); 
//-->new str :hello

十进制转十六进制:

NSLog(@"十进制转十六进制 --->%@",[NSString stringWithFormat:@"%x",255]);

或者:

+(NSString *)ToHex:(long long int)tmpid
{
    NSString *nLetterValue;
    NSString *str =@"";
    long long int ttmpig;
    for (int i = 0; i<9; i++) {
        ttmpig=tmpid%16;
        tmpid=tmpid/16;
        switch (ttmpig)
        {
            case 10:
                nLetterValue =@"A";break;
            case 11:
                nLetterValue =@"B";break;
            case 12:
                nLetterValue =@"C";break;
            case 13:
                nLetterValue =@"D";break;
            case 14:
                nLetterValue =@"E";break;
            case 15:
                nLetterValue =@"F";break;
            default:nLetterValue=[[NSString alloc]initWithFormat:@"%lli",ttmpig];
                
        }
        str = [nLetterValue stringByAppendingString:str];
        if (tmpid == 0) {
            break;
        }     
    }
    return str;
}
posted @ 2020-06-02 16:46  萧蔷ink  阅读(646)  评论(0编辑  收藏  举报