1

An int32 is represented in computer memory with a size of 4 bytes (32 bits).

So, 32 bits have 1 sign bit and 31 data bits. But if 1st bit starts at 2^0, then the 31st bit should have 2^30, and the last bit is of course the sign bit.

How is it then that integer extends from -2^31 to (2^31)-1?

Spandan
  • 33
  • 1
  • 6

2 Answers2

1

So, 32 bits have 1 sign bit and 31 data bits.

No. Most platforms use two's complement to represent integers.

This avoids double zero (+- 0) and instead extends the range of negative numbers by 1. The main advantage is in arithmetic: Many operations, like addition and subtraction can simply ignore the sign.

Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
  • 3
    I wouldn't say "no" : even in 2's complement representation, the official terminology is still 1 sign bit and 31 value bits. The difference between 2's complement and other representations is the meaning of the value bits in the case that the sign bit is set. – M.M Sep 11 '15 at 06:51
  • OK, maybe a *no* is a bit too harsh. Anyway, I wanted to make clear that this is the core of the OP's confusion: It's not a sign bit that just inverts the value of the rest of the bits. – Nikolai Ruhe Sep 11 '15 at 06:58
  • @M.M Saying "sign bit" and "value bits" is not accurate. A true sign bit would alter the meaning of the other bits, like in floating point where it means "change the value represented by the other bits from positive to negative." But that's not how it is with 2s complement. The value of an N-bit 2s complement number is the sum of the values represented by each of its 1 bits: Bit 0 is worth 1, bit 1 is worth 2, bit 2 is worth 4,... until you get to bit N-1 which is worth _minus_ 2^(N-1). The high order bit doesn't change the meaning of the others, it merely adds its value to their sum. – Solomon Slow Sep 11 '15 at 17:17
  • @jameslarge See section 6.2.6.2/2 of [the C standard](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf). Those are the official terms. The sign bit is `1` for negative numbers, and `0` for zero and positive numbers. – M.M Sep 11 '15 at 22:42
1

An int32 has exactly 32 bits, and can hold 2^32 different values.

In unsigned form, these will be 0 -> (2^32)-1.
In signed form, these will be -2^31 -> (2^31)-1. Notice that:

(0 - (-2^31)) + ((2^31)-1 - 0) =
2^31 + 2^31 - 1 =
2*2^31 - 1 =
(2^32) - 1

Exactly the same range.

Amit
  • 45,440
  • 9
  • 78
  • 110