Sample Source Code
Assume that the following is saved in a file convertInteger.nw. It is not an extensive example because the level of documentation
and explanation is fairly sparse, it is just for illustrative purposes only.
\subsection{Convert string to decimal string using prefixed notation}
The input string is in prefix (16r, (10r), 8r, 2r) notation. It returns
a decimal number.
<<*>>=
+ (int) convertInteger: (NSString*) inString
{
<<if string is null then exit with 0>>
<<Find where the prefix character is in the string>>
if ( radixRange.location == NSNotFound) {
<<decimal string found so return integer value directly>>
} else {
<<radix value found so process remainder of string>>
}
return returnValue;
} // convertInteger
@
We could return [[null]] here if returning [[NSInteger]].
<<if string is null then exit with 0>>=
if ( inString == NULL ) return 0;
@
<<Find where the prefix character is in the string>>=
NSRange radixRange = [inString rangeOfString:@"r"];
@ %def radixRange
<<decimal string found so return integer value directly>>=
return (int)[inString integerValue];
@
<<radix value found so process remainder of string>>=
<<extract the prefix radix>>
<<set up return value>>
<<Set up loop variables>>
for ( int i = (int)radixLength+1; i < [inString length]; i++ ) {
<<get next character into a string value>>
<<get character range from list of possible digits>>
<<add the digit to the return value>>
}
@
[[nextChar]] is a convenience variable to make things easier to read.
<<get next character into a string value>>=
s = [NSString stringWithFormat:@"%c", [inString characterAtIndex:i]];
@
To pull the correct value from the list of characters.
<<Set up loop variables>>=
NSRange charRange;
@ %def charRange
The range result (location) will be the multiplier for the radix.
<<get character range from list of possible digits>>=
charRange = [ @"0123456789ABCDEF"
rangeOfCharacterFromSet: [NSCharacterSet
characterSetWithCharactersInString: s]];
@
<<add the digit to the return value>>=
returnValue = radix * returnValue + (int)charRange.location;
@
Another convenience variable.
<<Set up loop variables>>=
NSString *s;
@ %def s
<<extract the prefix radix>>=
NSUInteger radixLength = radixRange.location;
NSString *radixString = [inString substringToIndex:radixLength];
int radix = [radixString intValue];
@ %def radix radixLength radixString
<<set up return value>>=
int returnValue = 0;
@ %def returnValue