C Programming - Bitwise Operators - Discussion

Discussion Forum : Bitwise Operators - Find Output of Program (Q.No. 4)
4.
If an unsigned int is 2 bytes wide then, What will be the output of the program ?
#include<stdio.h>

int main()
{
    unsigned int a=0xffff;
    ~a;
    printf("%x\n", a);
    return 0;
}
ffff
0000
00ff
ddfd
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
47 comments Page 2 of 5.

Priya said:   1 decade ago
~ is a unary operator.

Then it should have operated on a and saved the result in the same variable. But why isn't it happening?

Can anyone explain?

Deepak Kumar Dubey said:   1 decade ago
int i=4, j=8;

printf("%d %d %d\n",i|j&j|i,i|j&&j|i,i^j);

Can some explain me the way above question going to work.

Amrit sharma said:   1 decade ago
@Deepak.

1st (i|j&j|i).
Where i = 4= 0100(binary) and j = 8 = 1000(binary).
Now i|j where'|' is OR operator i.e it will 1100(12).
Similarly j|i will be 1100(12).

Now i|j&j|i where '&' operator as AND operator
1100(i|j)
& 1100(j|i)
1100(i|j&j|i) i.e 12.

Now second(i|j&&j|i)

Hence (12&&12) where '&&' is logical operator which output is either 0 or 1.

Hence here Rvalue = Lvalue so it is true.
is 1. so print 1.

Now 3rd (i^j) where '^' is XOR operator
i = 4 (0100)
^ j = 8 (1000)
(i^j) 1100.

So output is as 12 1 12 respectively.

Don no 1 said:   1 decade ago
Here ~a is used but not assign a value back to a so that a will not be affected.

Poulami said:   1 decade ago
What is the meaning of 0x..?

Shan said:   1 decade ago
What does 0Xfff represents? can anyone explain clearly?

Anu said:   1 decade ago
Like other unary operator they store the resultant value in operand itself on which the unary operator is applied.

For example a =7 and ++a stores 8 in a so why doesn't ~a stores the result in a.

Gopi krishna said:   1 decade ago
Thank you @Taruna.

I satisfy with you answer. What about two byte compiler?

Risv said:   1 decade ago
a = 1111 1111 1111 1111

Let b =~ a, means b = 0000 0000 0000 0000

[
Concept : take composite resultant value is b = (-1)*(a+1).
Here 'a' may be +/- in the form of Decimal value.
]

From above eg:

a = 0xffff.

a = -1 [decimal value of 0xffff].

So due to our concept b =~a => b = (-1)*(-1+1) therefor resultant of b = 0

b = 0 [means hexadecimal value is 0000 0000 0000 0000].

But here from above example:

Line 1: a = 1111 1111 1111 1111

Line 2: ~a = 0000 0000 0000 0000

But value of 'a' does not change in line 2.

So a = 0xffff.

Zeba Anwar said:   1 decade ago
Here a = 0*ffff.
Which can also be written as 0000ffff.

So ~a = ffff0000.
Therefore output will be ffff.


Post your comments here:

Your comments will be displayed after verification.