How do unsigned integers work

前端 未结 3 897
情书的邮戳
情书的邮戳 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 21:49

    When you assign a negative number

    unsigned int = -1;
    

    The number you got will be 4294967295, or 4^8 -1

    because the size of integer is 4bytes, or 4^8 = 4294967296

    The integer will wrap around this number if it is negative

    0 讨论(0)
  • 2021-01-13 22:02

    In answer to your first code example, the loop will compile (though will raise a warning if you are compiling with gcc and have the -Wno-sign-compare flag). Running it, however, will generally result in the loop not running at all since most systems use Two's complement (http://en.wikipedia.org/wiki/Two%27s_complement) which means -10 is the same as 4294967286 (assuming 4 byte integers but in general 2*INT_MAX - 10) which is greater than 5. In general, I recommend reading up on Two's complement as it will probably answer all your questions on the matter.

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
提交回复
热议问题