Search code examples
ccastingtype-conversionsigned

Cast signed char to unsigned int in C


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


Solution

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

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