How does the compiler treat printing unsigned int as signed int?
I am trying to understand why the following code:
{
unsigned int a = 10;
a = ~a;
printf("%d\n", a);
}
a
will be 00001010
for a start, and after NOT opertaion converts
in 11110101
.
What happens when you try to print a
as a signed integer, which does
will the printed result be -11
?
I thought I would eventually see -5
possibly (according to binary representation), but not -11
.
I would be glad to receive clarifications on this issue.
source to share
2's complement note is used to store negative numbers.
Number 10 - 0000 0000 0000 0000 0000 0000 0000 1010 in 4-byte binary format.
a = ~ a makes the content of a as 1111 1111 1111 1111 1111 1111 1111 0101.
This number, when treated as a signed int, tells the compiler to take the most significant bit as a sign and rest as a value.
The 1 in msb makes the number negative.
Therefore, 2 additional operations are performed on the remaining bits.
So 111 1111 1111 1111 1111 1111 1111 0101 becomes 000 0000 0000 0000 0000 0000 0000 1011.
This, when interpreted as a decimal integer, becomes -11.
source to share
When you write a = ~a;
, you change every bit in a, which is also called 1's complement.
The representation of a negative number is declared as implementation dependent, which means that different architectures may have different representations for -10
or -11
.
Assuming a shared processor 32 architecture that uses 2's complement to represent negative -1 numbers would be represented as FFFFFFFF (hexadecimal) or 32 bits in 1.
~a
will be represented as = FFFFFFF5
or in binary 1...10101
, which is the representation of -11.
Nota: the first part is always the same and is implementation independent, ~a
FFFFFFF5
for any 32-bit architecture. It only depends on the second part (-11 == FFFFFFF5
). BTW would be -10 on an architecture that would use 1's complement to represent negative numbers.
source to share