Converting a octal String to Decimal in Objective-C?

强颜欢笑 提交于 2019-12-23 09:29:52

问题


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!


回答1:


The cleanest solution is probably:

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

or

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



回答2:


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.




回答3:


Alternatively, if you want to drop down to C, you can use sscanf

int oct;
sscanf( [yourString UTF8String], "%o", &oct );


来源:https://stackoverflow.com/questions/12818305/converting-a-octal-string-to-decimal-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!