nikel
nikel

Reputation: 3564

Understanding Sign extension

int main()
{
  unsigned int b;
  signed int a;
  char z=-1;
  b=z;
  a=z;
  printf("%d %d",a,b);
}

gives -1 -1. why does no sign extension occur, ALSO, when does it occur?

Upvotes: 3

Views: 303

Answers (2)

progrmr
progrmr

Reputation: 77191

Sign extension DID occur, but you are printing the results incorrectly. In your printf you specified %d for b, but b is unsigned, you should have used %u to print b.

printf does not know the type of its arguments and uses the format specifies to interpret them.

printf("%d %u",a,b);

Upvotes: 10

Daniel A. White
Daniel A. White

Reputation: 190943

Because printf looks at the raw memory, not the type. use %u to print the value as unsigned.

See.

http://ideone.com/Qpcbg

Upvotes: 3

Related Questions