C Programming - Bitwise Operators - Discussion

Discussion Forum : Bitwise Operators - Find Output of Program (Q.No. 10)
10.
What will be the output of the program?
#include<stdio.h>

int main()
{
    printf("%d %d\n", 32<<1, 32<<0);
    printf("%d %d\n", 32<<-1, 32<<-0);
    printf("%d %d\n", 32>>1, 32>>0);
    printf("%d %d\n", 32>>-1, 32>>-0);
    return 0;
}
Garbage values
64 32
0 32
16 32
0 32
All zeros
8 0
0 0
32 0
0 16
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
42 comments Page 4 of 5.

Divya said:   1 decade ago
@vineet:

You are right. We have to consider 16 bits then -1 is represented as 16 '1's in 2's compliment. So it equals to (2 power 16)-1 if you shift by that many times the value of the exprssion is 0.

Vineet said:   1 decade ago
Hello,

Why are you all taking -1 as 8 bit number? I can't understand because by default every integer constant is of 16 bits.

NITESH said:   1 decade ago
Ok so -1 is being treated here as 256. Thanx Atul.

Raj Naik said:   1 decade ago
@Nikita

Negative numbers are treated with 2's complement method.

1's complement: Inverting the bits ( all 1s to 0s and all 0s to 1s)
2's complement: Adding 1 to the result of 1's complement

Hence

1111 1110 +
0000 0001
___________________
1111 1111 --> Which is equal to 256

Rashmi mate said:   1 decade ago
How is 32 << -1 is equal to 0 ? I'm unable to understand this.

Nikita said:   1 decade ago
2's comp of -1 is 1, how 256?

Apurva Nigam said:   1 decade ago
Thanks Atul.

Regi said:   1 decade ago
Can any one explain clearly?

Atul said:   1 decade ago
32 << -1 is nothing but 32 << 256 (2's complement of -1 in decimal notation) which will add 0 to all bit positions of 32.

Sundar said:   1 decade ago
Refer the explanation given following questions. You will understand it better way.

http://www.indiabix.com/c-programming/bitwise-operators/discussion-511

http://www.indiabix.com/c-programming/bitwise-operators/discussion-503

Hope this help you. Have a nice day!


Post your comments here:

Your comments will be displayed after verification.