Which bit wise operator is suitable for checking whether a particular bit is on or off?

Showing Answers 1 - 10 of 10 Answers

Its Bitwise AND (&)

for Ex, 
I need to check if 3rd bit from right(Starting from 0th) is ON in a variable x or OFF.
then see this code:
int x=24;
int tester=1;
tester = tester << 3; \Makes tester as 00001000
if((x&tester)!=1)
printf("3rd bit from left in x is ON");
else
printf("3rd bit from left in x is OFF");

Explaination:
x = 24 i.e.          0001 1000
tester = 1 i.e.    0000 0001
tester = tester << 3 does:
tester = 8 i.e.    0000 1000

now x&tester i.e.
0001 1000
&&&&&&&&
0000 1000
-------------
0000 1000
which is NON ZERO, hence decides that 3rd bit is SET / ON.

if x = 5 (0000 0101)
then x&tester i.e.
00000101   &
00001000
------------
00000000
which is ZERO, hence decides that 3rd bit is UNSET / OFF.


In Brief:
Bitwise AND is used to CHECK / TEST a particular bit.
Bitwise OR is used to SET (Make it 1) a particular bit.
Bitwise XOR is used to TOGGLE (1to0 or 0to1) a particular bit.
Bitwise AND is also used to RESET a particular bit (if ANDed with 11110111, say I have to reset 4th bit).

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions