Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a octal String to Decimal in Objective-C?

I trying to do conversions between Binary, Octal, Decimal and Hexadecimal in Objective-C. I had problems converting Octal to Decimal.

I have tried the following:

NSString *decString = [NSString stringWithFormat:@"%d", 077];

It works fine, returning 63 as expected, but my Octal value is a NSString. How can I tell the computer that it is a Octal;

I know there is a method called "scanHexInt:" which I used to convert Hexadecimal to decimal, but it seems there is no scanOctInt...

Any help would be appreciated!

like image 690
Keoros Avatar asked Oct 10 '12 11:10

Keoros


2 Answers

The cleanest solution is probably:

long result = strtol(input.UTF8String, NULL, 8);

or

long long result = strtoll(input.UTF8String, NULL, 8);
like image 97
mvds Avatar answered Sep 21 '22 23:09

mvds


Define a category on NSString (put this on top of any of your source code modules or into a new .m/.h file pair, @interface goes into .h, @implementation into .m):

@interface NSString (NSStringWithOctal)
-(int)octalIntValue;
@end

@implementation NSString (NSStringWithOctal)
-(int)octalIntValue
{
    int iResult = 0, iBase = 1;
    char c;

    for(int i=(int)[self length]-1; i>=0; i--)
    {
        c = [self characterAtIndex:i];
        if((c<'0')||(c>'7')) return 0;
        iResult += (c - '0') * iBase;
        iBase *= 8; 
    }
    return iResult;
}
@end

Use it like that:

NSString *s = @"77";
int i = [s octalIntValue];
NSLog(@"%d", i);

The method returns an integer representing the octal value in the string. It returns 0, if the string is not an octal number. Leading zeroes are allowed, but not necessary.

like image 25
nullp01nter Avatar answered Sep 23 '22 23:09

nullp01nter