Search code examples
objective-ccocoansstringunsigned

How to convert an NSString to an unsigned int in Cocoa?


My application gets handed an NSString containing an unsigned int. NSString doesn't have an [myString unsignedIntegerValue]; method. I'd like to be able to take the value out of the string without mangling it, and then place it inside an NSNumber. I'm trying to do it like so:

NSString     *myUnsignedIntString = [self someMethodReturningAString];
NSInteger    myInteger            = [myUnsignedIntString integerValue];
NSNumber     *myNSNumber          = [NSNumber numberWithInteger:myInteger];

// ...put |myNumber| in an NSDictionary, time passes, pull it out later on...

unsigned int myUnsignedInt        = [myNSNumber unsignedIntValue];

Will the above potentially "cut off" the end of a large unsigned int since I had to convert it to NSInteger first? Or does it look OK to use? If it'll cut off the end of it, how about the following (a bit of a kludge I think)?

NSString     *myUnsignedIntString = [self someMethodReturningAString];
long long    myLongLong           = [myUnsignedIntString longLongValue];
NSNumber     *myNSNumber          = [NSNumber numberWithLongLong:myLongLong];

// ...put |myNumber| in an NSDictionary, time passes, pull it out later on...

unsigned int myUnsignedInt        = [myNSNumber unsignedIntValue];

Thanks for any help you can offer! :)


Solution

  • The first version truncates and the second should be fine as long as your number actually fits into an unsigned int - see e.g. "Data Type Size and Alignment".
    You should however create the NSNumber using +numberWithUnsignedInt.

    If you know that the encoding is suitable, you could also simply go with the C-libraries:

    unsigned n;
    sscanf([str UTF8String], "%u", &n);