Adiel
Adiel

Reputation: 1215

How does the compiler treats printing unsigned int as signed int?

I'm trying to figure out why the following code:

{
  unsigned int a = 10;
  a = ~a;
  printf("%d\n", a);
}

a will be 00001010 to begin with, and after NOT opertaion, will transform

into 11110101.

What happens exactly when one tries to print a as signed integer, that makes

the printed result to be -11?

I thought i would end up seeing -5 maybe (according to the binary representation), but not -11.

I'll be glad to get a clarification on the matter.

Upvotes: 3

Views: 8830

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148870

When you write a = ~a; you reverse each an every bit in a, what is also called a complement to 1.

The representation of a negative number is declared as implementation dependant, meaning that different architectures could have different representation for -10 or -11.

Assuming a 32 architecture on a common processor that uses complement to 2 to represent negative numbers -1 will be represented as FFFFFFFF (hexadecimal) or 32 bits to 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 not implementation dependant, ~a is FFFFFFF5 on any 32 bits architecture. It is only the second part (-11 == FFFFFFF5) that is implementation dependant. BTW it would be -10 on an architecture that would use complement to 1 to represent negative numbers.

Upvotes: 2

Deepu
Deepu

Reputation: 7610

2's complement notation is used to store negative numbers.

The number 10 is 0000 0000 0000 0000 0000 0000 0000 1010 in 4 byte binary.

a=~a makes the content of a as 1111 1111 1111 1111 1111 1111 1111 0101.

This number when treated as signed int will tell the compiler to take the most significant bit as sign and rest as magnitude.

The 1 in the msb makes the number a negative number.

Hence 2's complement operation is performed on the remaining bits.

Thus 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.

Upvotes: 6

Related Questions