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 2 of 4.

Divya said:   9 years ago
We have different format specifiers for int - %d, float - %f, char - %c. etc.,

In the same way %x represents a hexagonal number.

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.

Bhai said:   6 years ago
We are taking the number as signed int.

so after getting ans as : fff8 should not we convert it into signed int also?

Wikiok said:   1 decade ago
2 : 00000000 00000010
-2 : 11111111 11111110 ( = ~2 +1 )
-2<<2: 11111111 11111000 so it is FFFF8

Kuro M said:   6 years ago
I understand the solution, but isn't shifting negative signed numbers to the left an undefined behavior?
(1)

Mausami said:   1 decade ago
But if there is negative then shifting means appending 1's rather than 0's.

Am I right ?

VENKAT said:   10 years ago
In above explanation why you added only two zeros please can you explain?

Vikranth said:   9 years ago
How the left shift is done for above problem can anyone explain it?

Gokulram said:   5 years ago
What is the meaning of f in that format ff8? Please explain.

Saisudha said:   1 decade ago
How is left shifting done? Can anyone please explain it?


Post your comments here:

Your comments will be displayed after verification.