Why does the range of int has a minus 1?

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

    Because the counting starts from 0

    And the range of int is 2,147,483,647 and 2^32 which is 2,147,483,648. hence we subtract 1

    Also the loss of 1 bit is for the positive and negative sign

    Check this interestinf wiki article on Integers:-

    The most common representation of a positive integer is a string of bits, using the binary numeral system. The order of the memory bytes storing the bits varies; see endianness. The width or precision of an integral type is the number of bits in its representation. An integral type with n bits can encode 2n numbers; for example an unsigned type typically represents the non-negative values 0 through 2n−1. Other encodings of integer values to bit patterns are sometimes used, for example Binary-coded decimal or Gray code, or as printed character codes such as ASCII.

    There are four well-known ways to represent signed numbers in a binary computing system. The most common is two's complement, which allows a signed integral type with n bits to represent numbers from −2(n−1) through 2(n−1)−1. Two's complement arithmetic is convenient because there is a perfect one-to-one correspondence between representations and values (in particular, no separate +0 and −0), and because addition, subtraction and multiplication do not need to distinguish between signed and unsigned types. Other possibilities include offset binary, sign-magnitude, and ones' complement.

提交回复
热议问题