I am trying to convert a NSInteger to a NSUInteger and I googled it and found no real answer. How would I do this?
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- back button text does not change
- iOS (objective-c) compression_decode_buffer() retu
- how to find the index position of the ARRAY Where
相关文章
- 现在使用swift开发ios应用好还是swift?
- TCC __TCCAccessRequest_block_invoke
- xcode 4 garbage collection removed?
- Unable to process app at this time due to a genera
- How can I add media attachments to my push notific
- didBeginContact:(SKPhysicsContact *)contact not in
- Custom Marker performance iOS, crash with result “
- Why is my library not able to expand on the CocoaP
Since this might be useful for other coming across this issue here is a little table showing you the actual effect of casting. These values were taken straight from the debugger as hex values. Choose accordingly, as you can see casting does cause effects. For 32-bit, lop off the bottom ffffffff and for 16-bit lop off bottom ffffffffffff. Also note, -1 is always 0xffffffffffffffff.
If you are certain that your
NSInteger
is greater than or equal to zero, you simply cast it asNSUInteger
. You should not be casting toNSUInteger
if yourNSInteger
represents a negative number, as it may lead to inconsistency.results in
If you are wanting to convert an integer to an unsigned integer, you are either in a situation where you know that the integer will never be negative, or you may be wanting all negative values to be converted to absolute values (i.e., unsigned values). Doing this conversion to an absolute value is straightforward:
fabs()
is a C function that returns an absolute value for any float. Here,myUnsignedInteger
would have a value of 100.Possible use cases for such a function would be display where you will indicate the negative values in a different format. For instance, in accounting negative numbers are displayed in parentheses:
Note that from a technical point of view, you could simply assign an NSInteger to an NSUInteger—this does not even require a cast—but when the NSInteger is negative the NSUInteger will return a very large positive number, which is clearly a highly undesirable side effect:
NSInteger
andNSUInteger
are just typedefs for primitive integer types:As such, you don't need to "convert" between them. A simple cast should be sufficient. Like: