Home > Net >  standard type conversion of an int to an unsigned int in C
standard type conversion of an int to an unsigned int in C

Time:05-10

I tried to change the type of a value like -1 (int) into an unsigned int. I tried this code

int main () {
 int a = -1;
unsigned int b;
b = a;
  cout << b;
  return 0;
}

the result was : 4294967295 but I assumed that the -1 as a 32 bit int is like: 10000000000000000000000000000001 and when it's going to be changed to unsigned it should be: 12^31 12^0 = 2147483649. what is wring with my thought?

CodePudding user response:

what is wring with my thought?

  1. Your assumption about representation of signed integers is wrong.

    You've described one possible representation, called "sign and magnitude". This representation was used by some systems built in the 1950's and 60's. All modern computer systems use another representation called "two's complement". In such representation -1 will be represented by all bits 1.

  2. Your assumption that the representation affects the result of the conversion is wrong.

    Whether a computer system uses particular sign representation or not, the behaviour of the conversion in C is same as on other systems. See the next segment.

  3. Your assumption about the result of the conversion is wrong.

    When you convert an unrepresentable value to unsigned, the result will be the representable value that is congruent with the original value modulo M, where M is the number of representable values in the usigned type which is maximum representable value 1.

    -1 is congruent with 4294967295 modulo 4294967296. This result is to be expected on those systems where the size of int is 32 bits.

CodePudding user response:

Even if the int was encoded as binary "10000000000000000000000000000001" (sign-magnitude), b is still 4294967295.

Conversion of an int to unsigned is not based on the encoding used by int. Instead, since the negative -1 is an out-of-range unsigned value, the maximum unsigned value 1 is added until the sum is within range.

Nothing to do with 2's complement or the other more rare int encodings. (IIRC non-2's complement is only allowed in older C these days.)

  • Related