C# Programming - Operators - Discussion

Discussion Forum : 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?
if ((n&16) == 16)
Console.WriteLine("Fourth bit is ON");
if ((n&8) == 8)
Console.WriteLine("Fourth bit is ON");
if ((n ! 8) == 8)
Console.WriteLine("Fourth bit is ON");
if ((n ^ 8) == 8)
Console.WriteLine("Fourth bit is ON");
if ((n ~ 8) == 8)
Console. WriteLine("Fourth bit is ON");
Answer: Option
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.

Discussion:
5 comments Page 1 of 1.

Kapil said:   1 decade ago
Hey can any one tell me. Why option B is right ?

Mohan said:   1 decade ago
Why we have use variable myByte and assign 153 value to it? can we assign any other value? Please someone explain.

Rajnish said:   1 decade ago
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:   9 years ago
Why mybyte = 153?

Garima said:   8 years ago
Bit count with 0 not 1.

Post your comments here:

Your comments will be displayed after verification.