Why does the range of int has a minus 1?

后端 未结 5 1724
夕颜
夕颜 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:52

    int is a signed data type. The first bit represents the sign, followed by bits for the value. If the sign bit is 0, the value is simply the sum of all bits set to 1 ( to the power of 2).

    e.g. 0...00101 is 20 + 22 = 5

    if the first bit is 1, the value is -232 + the sum of all bits set to 1 (to the power of 2).

    e.g. 1...111100 is -232 + 231 + 230 + ... + 22 = -4

    all 0 will this result in zero.

    When you calculate after, you will see that any number between (and including) the range - 231 and 20 + ... + 231 = 232 - 1 can be created with those 32 bits.

提交回复
热议问题