Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSUInteger string encoding 32 and 64 bit

I am trying to figure out the best way to convert an NSUInteger into a string that works for both 32- and 64-bit systems. I see that NSUInteger is defined differently for both platforms and I want to make sure what I am doing is correct.

All solutions I have seen required some casting, or seem incorrect. I get a warning with the code below asking me to add an explicit cast.

NSUInteger unsignedInteger = PostStatusFailed; // This is an enum
NSString *string = [NSString stringWithFormat:@"postStatus == %lu", unsignedInteger];

I have also tried %d (signed ints, which doesn't seem correct), and %lx, but none seem correct. Thanks.

like image 533
James Paolantonio Avatar asked Jan 30 '26 17:01

James Paolantonio


1 Answers

From the String Programming Guide:

OS X uses several data types—NSInteger, NSUInteger,CGFloat, and CFIndex—to provide a consistent means of representing values in 32- and 64-bit environments. In a 32-bit environment, NSInteger and NSUInteger are defined as int and unsigned int, respectively. In 64-bit environments, NSInteger and NSUInteger are defined as long and unsigned long, respectively. To avoid the need to use different printf-style type specifiers depending on the platform, you can use the specifiers shown in Table 3. Note that in some cases you may have to cast the value.

See the link for all of the types. For NSUInteger, the correct approach is:

NSUInteger i = 42;
NSString *numberString = [NSString stringWithFormat:@"%lu is the answer to life, the universe, and everything.", (unsigned long)i];
like image 106
Aaron Brager Avatar answered Feb 02 '26 06:02

Aaron Brager