How do unsigned integers work

前端 未结 3 898
情书的邮戳
情书的邮戳 2021-01-13 21:13

As the title suggests, I am curious about how an unsigned int (or things like NSUInteger, u_int_blah, but I assume these are all

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-13 22:03

    When a unsigned comparing with signed, they will all be cast into unsigned. The procedure is relative to how the data is stored in memory. In binary, a minus number( like -3), will be stored like :

    -3 : 1111 1111 1111 1101
    3  : 0000 0000 0000 0011
    

    you can tell that -3 can be like :

    // result  : 0000 0000 0000 0011
    
    result = for_every_bit_of_3( not **ThisBit** );  
    // result  : 1111 1111 1111 1100 
    
    result = result + 1;
    // result  : 1111 1111 1111 1101 
    

    So the loop:

    for (unsigned int x = 5; x > -10; x--) {
        // will x ever reach below zero, or will the loop terminate
    }
    

    will be like

    // 4,294,967,286 is what -10 cast to unsigned
    for (unsigned int x = 5; x > 4294967286; x--) {
        // will x ever reach below zero, or will the loop terminate
    }
    

提交回复
热议问题