Convert octal string to decimal in Objective-C?

I am trying to do conversions between binary, octal, decimal and hexadecimal in Objective-C. I had problems converting Octal to Decimal.

I tried the following:

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

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

I know there is a method called "scanHexInt:" that I used to convert hex to decimal, but there seems to be no scanOctInt ...

Any help would be appreciated!

+6
source share
3 answers

The cleanest solution is probably:

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

or

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

Define a category in NSString (put this on top of any of the source code modules or in a new pair of .m / .h files, @interface goes into .h, @implementation in .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 this:

 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 zeros are allowed, but not required.

+3
source

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

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

Source: https://habr.com/ru/post/927344/


All Articles