C++ integer overflow

前端 未结 4 1387
小蘑菇
小蘑菇 2020-12-10 20:54

I\'m just starting to teach myself C++, and have begun learning about integer overflow. Out of curiosity I wrote some tests just to see what occurs with certain integer valu

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-10 21:45

    Integers (generally) take a 32-bit representation. If you have 32 bits, you can address from 0 to 231-1. i.e.,

    00000000000000000000000000000000
    00000000000000000000000000000001
    .
    .
    .
    01111111111111111111111111111111
    ^-------------------------------
    signed bit
    

    0 indicates a positive number, 1 indicates a negative number.

    If you add 1 to 01111111111111111111111111111111, you get 10000000000000000000000000000000, which is -2147483648 in decimal.

    Using an unsigned integer, there's no signed bit and, ipso facto, can have a number twice as large as your largest signed integer. However, when the number rolls over again (i.e., 11111111111111111111111111111111 + 00000000000000000000000000000001), you simply roll back to 00000000000000000000000000000000.

    For a more in depth understanding, you can look at two's complement, which is how integers are represented in computers.

提交回复
热议问题