2

New to C and today learned int but confused about the smallest integer as -2^31 = -2147483648.

To my shallow understanding with decimal, for a 4-digit number, its largest is 10^4-1 = 9999 and its smallest -(10^4-1) = -9999. The smallest can’t be -(10^4) = -10000 as it will be 5-digit. (Maybe this is a wrong analogy but this is the closest thing I can relate...)

I must have missed something but failed to think it through. Much appreciated if someone could shed some light here. Thanks!

C-lv1
  • 21
  • 1
  • 2
    https://en.wikipedia.org/wiki/Computer_number_format#Binary_number_representation – GSerg Dec 22 '20 at 13:33
  • 1
    You assume that the sign is stored in addition to your 4 decimal digits. That is not the case with binary numbers. The information about the sign is part of the 32 bits. – Gerhardh Dec 22 '20 at 13:35
  • 2
    You did not tell us what you expected to be the correct value. Maybe you confused 2^31 and 2^32? – Gerhardh Dec 22 '20 at 13:36
  • 1
    "-(10^4-1) = -9999." is the right start. Now think binary and 31 digits (+ 1 bit for the sign). – chux - Reinstate Monica Dec 22 '20 at 13:40
  • 4
    Consider a signed 8-bit number (2's complement). It can store 2^8 = 256 different values, and these are -128 to +127. – Weather Vane Dec 22 '20 at 13:42
  • `-9999` is not a 4 digit number. If you are going to allow a sign, then that would be 4 digits plus a sign (eg, a 4.1 digit number, or a 5 digit number, or a 17 bit number, depending on your perspective and some definitions). – William Pursell Dec 22 '20 at 14:12
  • The analogy in four-digit decimal numbers is that “0000” to “4999” represent the numbers 0 to 4999 and “5000” to “9999” represent negative numbers. In this ten’s complement system, “9999” represents −1, “9998” represents −2, and, for any numeral in “5000” to “9999” that would represent *x* in plain decimal, in ten’s complement, it represents *x* − 10000. So “5000” represents 5000−10000 = −5000. – Eric Postpischil Dec 22 '20 at 14:25
  • There are different ways to represent signed integers, of which 2’s complement is the most common. In this system the leading bit is used to represent the sign - 0 for non-negative and 1 for negative. For example, a 3-bit type can represent 8 values - 4 negative values (`-4` to `-1`) and four non-negative values (`0` to `3`). In general, you wind up with the range `[-2^(N-1)..2^(N-1)-1]`. In other systems you have two representations for `0`, but they’re not very common. – John Bode Dec 22 '20 at 14:49

0 Answers0