C# Programming - Operators - Discussion

Discussion :: Operators - General Questions (Q.No.10)

10. 

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?

[A].
if ((n&16) == 16)
Console.WriteLine("Fourth bit is ON");
[B].
if ((n&8) == 8)
Console.WriteLine("Fourth bit is ON");
[C].
if ((n ! 8) == 8)
Console.WriteLine("Fourth bit is ON");
[D].
if ((n ^ 8) == 8)
Console.WriteLine("Fourth bit is ON");
[E].
if ((n ~ 8) == 8)
Console. WriteLine("Fourth bit is ON");

Answer: Option B

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.


Kapil said: (Aug 1, 2011)  
Hey can any one tell me. Why option B is right ?

Mohan said: (May 2, 2013)  
Why we have use variable myByte and assign 153 value to it? can we assign any other value? Please someone explain.

Rajnish said: (Oct 30, 2013)  
Answer: n is variable type is byte.
1 Byte = 8 bit
n = 8;

a)16 in binary:000001.
8 in Binary :000010.

if((n&16) == 16).
(000001 & 000010=000011).
(8 & 16 ==24).
Which not true.
Wrong option.

b) if((n& 8) == 8 ).
(8 & 8 == 8).
(00001 & 00001 =00001).
Its true.

Sai said: (Feb 25, 2016)  
Why mybyte = 153?

Garima said: (Apr 16, 2017)  
Bit count with 0 not 1.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.