How to convert NSString to unsigned int in Cocoa?

My application gets an NSString containing an unsigned int . NSString does not have a method [myString unsignedIntegerValue]; . I would like to be able to extract a value from a string without distorting it, and then place it inside NSNumber . I am trying to do it like this:

 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 ? Or does it look normal? If this cuts off the end, then what about the next one (a bit like kludge)?

 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! :)

+6
objective-c cocoa nsstring unsigned
source share
1 answer

The first version is truncated, and the second one is fine as long as your number really fits into the unsigned int - see, for example, "Size and Alignment of a Data Type" .
However, you must create an NSNumber using +numberWithUnsignedInt .

If you know the encoding is suitable, you can also just go with the C libraries:

 unsigned n; sscanf([str UTF8String], "%u", &n); 
+6
source share

All Articles