In this blog |
---|
bitwise operators |
bitwise operators
operator | meaning |
& | bitwise and |
| | bitwise or |
~ | bitwise not |
^ | bitwise Xor |
<< | bitwise leftshift |
>> | bitwise rightshift |
bitwise and (&)
A | B | A&b |
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
conclusion is that if both bit of nth position would are true then the nth bit in the output would be true.
eg
printf("%d", A&B) // A=2 ,B=3 output would be 2
why output would be 2?
as it will compare each bit of A with B , in binary value of A and B would be
0010 , 0011 respectively , now compare each bit of A with B using the above given table. the output would be 0010.
bitwise or ( | )
A | B | A|b |
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 1 |
conclusion is that if one bit of nth position is true then the nth bit in the output would also be true.
eg
printf("%d", A|B)// A=2 ,B=0 output would be 2
bitwise not ( ~ )
A | ~A |
0 | 1 |
1 | 0 |
bitwise not operator reverses each bit of a given no
eg
printf("%d", ~A) // A=1 output would be -2
how did we get the above output , for explanation visit...
link
bitwise Xor ( ^ )
A | B | A&b |
1 | 0 | 1 |
0 | 1 | 1 |
0 | 0 | 0 |
1 | 1 | 0 |
eg
printf("%d", A^B) // A=2, B=3 output would be 1
xor operator gives 1 as an output if the bit of operand are different ,A =0010 , B=0011 on 0the position from right bit is diffrent so 1 and on 1,2,3 position bits are same so 0 , so answer is 0001
bitwise leftshift and rightshift(<< , >>)
bitwise leftshift or rightshift is used to shifts the bit to right or left by a specified no
syntax :
operand << no of bits you want to shift
eg
printf("%d", A<<2); // A=2 output would be 8
A is 0010 so after shifitng is looks like 1000 which is 8 ( every bit is shifted to right by 2 and left most 2 bits are lost and on right 2 bits are added)
same applies for rightshift also.
( note : for calculating mannualy formula for left shift is A * 2 no of bits that you want to shift for right shift you had to divide A / 2 no of bits that you want to shift )
No comments:
Post a Comment