Home » C# Programming » Operators

Suppose n is a variable of the type Byte and we wish, to check whether its fourth bit (from right) is ON or OFF. Which of the following statements will do this correctly?

Correct Answer: if ((n&8) == 8) Console.WriteLine("Fourth bit is ON");

Explanation:

byte myByte = 153; // In Binary = 10011001

byte n = 8; // In Binary = 00001000 
(Here 1 is the 4th bit from right)

Now perform logical AND operation (n & myByte)

 10011001
 00001000
---------
 00001000  Here result is other than 0, so evaluated to True.
---------
If the result is true, then we can understand that 4th bit is ON of the given data myByte.

← Previous Question Next Question→

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion