Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 933
Kyle Rohlfing Avatar asked Feb 22 '14 01:02

Kyle Rohlfing


People also ask

How do you convert a signed integer to an unsigned integer?

To convert a signed integer to an unsigned integer, or to convert an unsigned integer to a signed integer you need only use a cast. For example: int a = 6; unsigned int b; int c; b = (unsigned int)a; c = (int)b; Actually in many cases you can dispense with the cast.

What happens when you cast signed to unsigned in C?

The answer to this question is that nothing happens because according to the C99 standard if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

Can you cast a char to an int in C?

There are 3 ways to convert the char to int in C language as follows: Using Typecasting. Using sscanf() Using atoi()

Can you cast unsigned char to char?

However, from i=128:255 the chars and the unsigned chars cannot be casted, or you would have different outputs, because unsigned char saves the values from [0:256] and char saves the values in the interval [-128:127]).


2 Answers

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.

like image 143
Arkku Avatar answered Sep 30 '22 05:09

Arkku


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

printf("n: %u", n);
like image 30
Yu Hao Avatar answered Sep 30 '22 05:09

Yu Hao