Search code examples
iphonensstringoctal

Convert NSString with octal numbers to decimal int


I have an NSString with octal numbers:

NSString* octal = @"247";

I'd like to convert this to an integer in base 10.

If this were a hex number I could use NSScanner scanHex method, but there is no scanOct...

Thanks!


Solution

  • The standard C library has conversion functions for this purpose:

    NSString* octal = @"247";
    
    unsigned long value;
    sscanf([octal UTF8String], "%lo", &value);
    
    NSString* decimal = [@(value) stringValue];
    

    decimal now contains the converted base 10 value.