Given N bits, how many integers can be represented in binary?

后端 未结 2 1392
傲寒
傲寒 2021-01-29 05:15

Suppose you have 14 bits. How do you determine how many integers can be represented in binary from those 14 bits?

Is it simply just 2^n? So 2^14 = 16384?

Please

2条回答
  •  灰色年华
    2021-01-29 06:11

    The answer depends on whether you need signed or unsigned integers.

    If you need unsigned integers then using 2^n you can represent integers from 0 to 2^n exclusive. e.g. n=2; 2^2=4 you can represent the integers from 0 to 4 exclusive (0 to 3 inclusive). Therefore with n bits, you can represent a maximum unsigned integer value of 2^n - 1, but a total count of 2^n different integers including 0.

    If you need signed integers, then half of the values are negative and half of the values are positive and 1 bit is used to indicate whether the integer is positive or negative. You then calculate using using 2^n/2. e.g. n=2; 2^2/2=2 you can represent the integers from -2 to 2 exclusive (-2 to +1 inclusive). 0 is considered postive, so you get 2 negative values (-2, -1) and 2 positive values (0 and +1). Therefore with n bits, you can represent signed integers values between (-) 2^n/2 and (+) 2^n/n - 1, but you still have a total count of 2^n different integers as you did with the unsigned integers.

提交回复
热议问题