Question

Can anyone explain to me why the following code outputs -50 even though it is being cast to an unsigned int?

int main()
{
  signed char byte = -50;
  unsigned int n;

  n = (unsigned int) byte;

  printf("n: %d", n);
}

output: -50

Was it helpful?

Solution 2

The cast is correct, but you are printing it incorrectly. %d in printf() is for int, change it to:

printf("n: %u", n);

OTHER TIPS

Assigning -50 to unsigned int causes the integer to wrap around, and this wrapped around unsigned int has the same bits set as the signed int corresponding to -50 in the twos complement representation that is used by almost every computer.

Now, printf is a function with a variable number of arguments that it interprets according to the format string. The format %d is for signed ints and printf has no way of knowing that the corresponding argument is actually an unsigned int (because you told it otherwise). So the bits get interpreted as though it were signed int and you get -50.

Even with printf("n: %u", n); , you are not going to get 50.

see the link int to unsigned int conversion

With your statement:

printf("n: %d", n); 

you are casting it to "Signed decimal integer"

if you try

std::cout<<n<<std::endl;

you will see that you won't get -50

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top