Kyle Rohlfing
Kyle Rohlfing

Reputation: 65

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

Upvotes: 5

Views: 6836

Answers (4)

Arkku
Arkku

Reputation: 42139

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.

Upvotes: 6

zee
zee

Reputation: 188

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

see the link int to unsigned int conversion

Upvotes: 2

user1767754
user1767754

Reputation: 25094

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

Upvotes: 1

Yu Hao
Yu Hao

Reputation: 122383

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

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

Upvotes: 5

Related Questions