Convert NSInteger to NSUInteger?

前端 未结 4 858
天涯浪人
天涯浪人 2021-02-04 00:30

I am trying to convert a NSInteger to a NSUInteger and I googled it and found no real answer. How would I do this?

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 01:27

    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:

    NSInteger mySignedInteger = -100;
    NSUInteger myUnsignedInteger = fabs(mySignedInteger);
    

    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:

    NSString * numberForDisplay;
    if (mySignedInteger < 0) {
        numberForDisplay = [NSString stringWithFormat:@"(%lu)", myUnsignedInteger];
    } else {
        numberForDisplay = [NSString stringWithFormat:@"%lu", myUnsignedInteger];
    }
    

    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:

    NSUInteger myUnsignedInteger = mySignedInteger;
    

提交回复
热议问题