Re: -hexValue for NSString?
Re: -hexValue for NSString?
- Subject: Re: -hexValue for NSString?
- From: Ali Ozer <email@hidden>
- Date: Mon, 23 Mar 2009 23:19:34 -0700
NSString's intValue and related methods are conveniences, for quick-
and-dirty extraction of the desired value, with limited flexibility
and no real error checking.
If you want to do error checking, or do a little more sophisticated
scanning (like extracting multiple values, etc), you would want to use
the NSScanner approach. And in fact instead of creating a temporary,
throw-away scanner like I did in my first example, you would create
one and make multiple calls to it. For instance, to extract 3 hex
values and make sure that's all there is:
unsigned val1, val2, val3;
NSScanner *scanner = [NSScanner scannerWithString:string];
if ([scanner scanHexInt:&val1] && scanner scanHexInt:&val2] &&
[scanner scanHexInt:&val3] && [scanner isAtEnd]) { ... success ... }
Ali
On Mar 23, 2009, at 8:11 PM, Jonathon Kuo wrote:
Kewl, two excellent solutions! Cocoa is pretty versatile.
I have alot to learn yet but I don't quite have my head around why
its more "Cocoaish" to invoke a class like NSScanner on an external
object (Ali's approach) versus expecting the NSString object to be
able to render its own contents in a format I'd like (Dave's
approach)?
Thanks Ali and Dave!
On Mar 23, 2009, at 6:16 PM, Ali Ozer wrote:
NSScanner has
- (BOOL)scanHexInt:(unsigned *)value; // Optionally prefixed with
"0x" or "0X"
- (BOOL)scanHexLongLong:(unsigned long long *)result;
so you can
unsigned yourValueHere;
BOOL success = [[NSScanner scannerWithString:string]
scanHexInt:&yourValueHere];
Ali
On Mar 23, 2009, at 6:00 PM, Jonathon Kuo wrote:
In NSString theres -intValue, -floatValue, -doubleValue, but no -
hexValue (that I can find). I'd like to convert ascii hex
NSStrings (@"001A4CD3" etc) into integer values. Having a -
hexValue method would make that a snap. If theres no Cocoa way, I
guess I could try my hand at writing a category(?) method on
NSString using sscanf with %x.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden