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
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.
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.
There are 3 ways to convert the char to int in C language as follows: Using Typecasting. Using sscanf() Using atoi()
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]).
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 int
s 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
.
The cast is correct, but you are printing it incorrectly. %d
in printf()
is for int
, change it to:
printf("n: %u", n);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With