Q:NSString length负数比较问题

- (void) testStringLength {
    NSString * str = @"1111111111";
    NSLog(@"%d", -str.length);
    if (-str.length > 801) {
        NSLog(@"wrong");
    } else {
        NSLog(@"right");
    }
} 

LOG

2013-02-20 18:54:17.900 test[21134:f803] -10
2013-02-20 18:54:25.235 test[21134:f803] wrong

这是肿么回事?

解析:

- (void) testStringLength {
    NSString * str = @"1111111111";
    NSLog(@"%d", -str.length);
    long long temp = LONG_LONG_MAX;
    while (-str.length < temp) {
        temp /= 10;
        NSLog(@"%lld", temp);
    }
    
    temp *= 10;
    while (-str.length < temp) {
        temp /= 2;
        NSLog(@"%lld", temp);
    }
    
    temp *= 2;
    while (-str.length < temp) {
        temp -= temp / 3;
        NSLog(@"%lld", temp);
    }
    
    if (-str.length < temp) {
        NSLog(@"wrong");
    } else {
        NSLog(@"right");
    }
} 

LOG:

2013-02-21 11:50:01.190 test[2183:f803] -10
2013-02-21 11:50:01.195 test[2183:f803] 922337203685477580
2013-02-21 11:50:01.195 test[2183:f803] 92233720368547758
2013-02-21 11:50:01.195 test[2183:f803] 9223372036854775
2013-02-21 11:50:01.196 test[2183:f803] 922337203685477
2013-02-21 11:50:01.196 test[2183:f803] 92233720368547
2013-02-21 11:50:01.197 test[2183:f803] 9223372036854
2013-02-21 11:50:01.197 test[2183:f803] 922337203685
2013-02-21 11:50:01.197 test[2183:f803] 92233720368
2013-02-21 11:50:01.198 test[2183:f803] 9223372036
2013-02-21 11:50:01.198 test[2183:f803] 922337203
2013-02-21 11:50:01.198 test[2183:f803] 4611686015
2013-02-21 11:50:01.199 test[2183:f803] 2305843007
2013-02-21 11:50:01.199 test[2183:f803] 3074457343

分析:

-str.length 大小应该在最后2个数之间,比LONG_MAX:2147483647大一些

- (NSUInteger)length;

length返回是一个无符号的int,-str.length貌似强行转换成了NSUInteger



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值