I haven't been able to figure out how to convert a NSString to an int. I'm trying to convert ASCII to text, but to do that I need to convert a string to an int.
I find it really strange that this isn't anywhere online or in stack overflow. I'm sure I'm not the online one who needs this.
Thanks in advance for helping.
P.S. If this helps here is the code I'm using to convert to ASCII:
+ (NSString *) decodeText:(NSString *)text {
NSArray * asciiCode = [text componentsSeparatedByString:@"|"];
int i = 0;
NSMutableString *decoded;
while (i < ([asciiCode count]-1) ) {
NSString *toCode = [asciiCode objectAtIndex:i];
int codeInt = toCode;
NSString *decode = [NSString stringWithFormat:@"%c", codeInt];
[decoded appendString:decode];
}
return decoded;
}
To parse string to integer you should do:
NSString *a = @"123abc";
NSInteger b = [a integerValue];
Perhaps fractionally off-topic, but to convert to ASCII you could just use:
[NSString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]
Or in your example:
return [text dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
This will return an NSData which you could iterate through to obtain a string representation of ASCII (s per your method) if this is what you require.
The reason for using this approach is because NSString's can store non-ASCII characters, you will of course potentially lose detail, but enabling the allowLossyConversion flag will attempt to overcome this. As per the Apple documentation:
For example, in converting a character from NSUnicodeStringEncoding to NSASCIIStringEncoding, the character ‘Á’ becomes ‘A’, losing the accent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With