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;
}
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.
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 1 of 4.
Kuro M said:
6 years ago
I understand the solution, but isn't shifting negative signed numbers to the left an undefined behavior?
(1)
Manju said:
7 years ago
Why did they shift 2 bits by left?
Can anyone tell me?
Can anyone tell me?
Vino said:
9 years ago
Why do we need to take 2's complement form?
Vino said:
9 years ago
Why we need to take 2's complement?
Tamilselvi said:
8 years ago
How it is equal to fff8?
Noshikifuka G said:
8 years ago
We need to take a 2's complement because the input is -2. Whenever the input has negative sign we need to take 2's complement.
Noshikifuka G said:
8 years ago
A=10, B=11,C=12.D=13,E=14,F=15 in hexa decimal.
11111111 11111000---> from left first 1111 is equal to 15 i.e f.
Next 1111 is equal to 15 i.e f then next 1111 is f so totally three f is present.
remaining part is 1000 that is equal to 8 so the ans is fff8.
11111111 11111000---> from left first 1111 is equal to 15 i.e f.
Next 1111 is equal to 15 i.e f then next 1111 is f so totally three f is present.
remaining part is 1000 that is equal to 8 so the ans is fff8.
Arun said:
7 years ago
00000000 00000010-- the binary value of 2.
In that why how many zeros are put before 1?
We normally do the value of 2 is 0010 we use only 8 why would we use & how many zeros?
In that why how many zeros are put before 1?
We normally do the value of 2 is 0010 we use only 8 why would we use & how many zeros?
Lilyjaiswal said:
7 years ago
How to it can print anything modifier for integer is %d?
Veera said:
7 years ago
Why added 2? Explain here.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers