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);

十进制转十六进制:

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;
}
上一篇:30分钟学会Objective-C


下一篇:熟悉编程语言