Why does the range of int has a minus 1?

后端 未结 5 1723
夕颜
夕颜 2021-02-15 11:17

I read that the range of an int is dependent on a byte.

So taking int to be 4 bytes long, thats 4 * 8 bits = 32 bits.

So the range should be : 2 ^ (32-1) = 2 ^ (

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-15 11:54

    Since integer is 32 bit. It could store total 2^32 values. So an integer ranges from -2^31 to 2^31-1 giving a total of 2^32 values(2^31 values in the negative range+2^31 values in positive range including 0).However, the first bit(the most significant bit) is reserved for the sign of the integer. Again u need to understand how negative integers are stored.They are stored in 2's complement form, So -9 will be stored as 2's complement of 9. So 9 is stored in 32 bit system as 0000 0000 0000 0000 0000 0000 0000 1001 and -9 will be stored as 1111 1111 1111 1111 1111 1111 1111 0111 (2's complement of 9).

    Again due to some arithmetic operation on an integer, if it happens to exceed the maximum value(2^31-1) then it will recycle to the negative values. So if you add 1 to 2^31-1 it will give you -2^31.

提交回复
热议问题