C Programming - Expressions - Discussion

Discussion Forum : Expressions - Find Output of Program (Q.No. 2)
2.
Assuming, integer is 2 byte, What will be the output of the program?
#include<stdio.h>

int main()
{
    printf("%x\n", -2<<2);
    return 0;
}
ffff
0  
fff8
Error
Answer: Option
Explanation:
The integer value 2 is represented as 00000000 00000010 in binary system.

Negative numbers are represented in 2's complement method.

1's complement of 00000000 00000010 is 11111111 11111101 (Change all 0s to 1 and 1s to 0).

2's complement of 00000000 00000010 is 11111111 11111110 (Add 1 to 1's complement to obtain the 2's complement value).

Therefore, in binary we represent -2 as: 11111111 11111110.

After left shifting it by 2 bits we obtain: 11111111 11111000, and it is equal to "fff8" in hexadecimal system.
Discussion:
33 comments Page 3 of 4.

Lilyjaiswal said:   7 years ago
How to it can print anything modifier for integer is %d?

Manju said:   7 years ago
Why did they shift 2 bits by left?

Can anyone tell me?

John said:   7 years ago
After shifting why can't it be 1111 1111 1111 1011?

Vamsi reddy said:   1 decade ago
Why is it, in hexadecimal form ? please explain.

Sowndarya said:   9 years ago
Hai, I have a doubt.

What is the use of %x?

Vino said:   9 years ago
Why do we need to take 2's complement form?

Swati said:   1 decade ago
How is shifting done ? please tell anyone.

Nani said:   1 decade ago
Why should we follow hexadecimal formats?

Vino said:   9 years ago
Why we need to take 2's complement?

Falcon said:   1 decade ago
@Sameer
In dev-c integer is 4 byte


Post your comments here:

Your comments will be displayed after verification.