Re: Convert hexadecimal NSString (0xff00) to decimal integer?
Re: Convert hexadecimal NSString (0xff00) to decimal integer?
- Subject: Re: Convert hexadecimal NSString (0xff00) to decimal integer?
- From: Daniel Ericsson <email@hidden>
- Date: Tue, 7 Jan 2003 17:20:05 +0100
On tisdag, jan 7, 2003, at 14:54 Europe/Stockholm, Greg Hurrell wrote:
I was rather surprised today when I couldn't find a way of converting
from an NSString containing a hexadecimal representation of a number
eg. something like "0xff00"
to a decimal integer of that number eg. 65280.
<snip>
I didn't want to "re-invent the wheel" so to speak, as this must
surely be a fairly common requirement. I searched around a bit,
couldn't find anything in Core Foundation to do it, nor any examples
on the web, so in the end I did indeed "re-invent the wheel".
So I made a category that extends NSString and adds a method called
-intValueFromHexadecimal. Now tell me if all that was a waste in
time... (although it was useful as a programming exercise for a
learner like me at least).
You didn't give any implementation details but I found it easy enough
to just use the libc funtion sscanf(), int sscanf(const char *str,
const char *format, ...);
#include <stdio.h>
int i;
NSString *aString = @"0xff00";
sscanf([aString cString], "%x", &i);
NSLog(@"i: %i", i);
Perhaps it's bleedingly obvious and staring me in the face, but I
couldn't find any shortcuts in NSString or NSNumber that might do this
conversion in one hit... and I find that odd because Apple obviously
has code which does this (if you look at the way their code can parse
plists it's evident they have plenty of tricks for converting between
various types of strings and numbers etc).
I agree, for completeness sake, there should be a way to get an integer
from a hexadecimal NSString using the Cocoa frameworks (if it's there I
can't see it either).
/Danne
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.