Converting a octal String to Decimal in Objective-C?
-
06-07-2021 - |
سؤال
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!
المحلول
The cleanest solution is probably:
long result = strtol(input.UTF8String, NULL, 8);
or
long long result = strtoll(input.UTF8String, NULL, 8);
نصائح أخرى
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.
Alternatively, if you want to drop down to C, you can use sscanf
int oct;
sscanf( [yourString UTF8String], "%o", &oct );