Consider the following C++ code:
#include <cstdio>
using namespace std;
int main()
{
int ia = -5;
unsigned int uia = ia;
char ca = -5;
unsigned char uca = ca;
printf("%d\n", (ia == uia));
printf("%d\n", (ca == uca));
return 0;
}
The output is
1
0
I don't understand what's the difference between int
and char
while casting from signed
to unsigned
?
Could you please enlighten me?
Mathematically, the conversion from signed to unsigned works as follows: (1) do the integer division of the signed integer by 1 + max , (2) codify the signed integer as the non-negative remainder of the division. Here max is the maximum integer you can write with the available number of bits, 16 in your case.
A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647]. An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295]. The signed integer is represented in twos complement notation.
Signed numbers use sign flag or can be distinguish between negative values and positive values. Whereas unsigned numbers stored only positive numbers but not negative numbers.
1) Add UINT_MAX + 1 to your signed number and store it in an unsigned variable. (this will convert the signed integer to an unsigned integer of same magnitude). 2) Unsigned number of same binary representation can be found by multiplying each digit in the binary representation by its place value and adding them up.
They both behave the same when converting from signed to unsigned. What behaves differently is the ==
comparison. It behaves as expected for the int/unsigned, but when you compare two smaller types, they both get promoted to int
first. So what happens is that the unsigned 8-bit representation of -5 and -5 both get promoted to int
and then get compared. These are obviously different and fail the comparison.
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