C# Programming - Operators - Discussion

Discussion Forum : Operators - General Questions (Q.No. 12)
12.
Suppose n is a variable of the type Byte and we wish to put OFF its fourth bit (from right) without disturbing any other bits. Which of the following statements will do this correctly?
n = n && HF7
n = n & 16
n = n & 0xF7
n = n & HexF7
n = n & 8
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
10 comments Page 1 of 1.

Karthik said:   1 decade ago
Can anyone explain how it is?

Vijay said:   1 decade ago
Please explain the result how it come?

Manoj said:   1 decade ago
Please explain it.

Teju MB said:   1 decade ago
Suppose your number is 10 i:e 1100 (in binary)
and u want to put off the fourth bit ,after that result should come as 0100
So for that we are doing AND operation with F7(1111 0111)
so the result will be

0000 1100 (10)
1111 0111 (F7)
(AND Operation)
----------------------
0000 0100 (Hence here the fourth bit has off now)

Teju MB said:   1 decade ago
& can be used to set the bit OFF and '|' can be used to set the bit ON

Nidhi said:   1 decade ago
Why ans is not "D--> HexF7" here!? What is the difference between prefix 0X and Hex ?

Civa said:   1 decade ago
Common way to do this is :

byte val = 159;
val = val & ( ~mask );

Where mask is our binary representation of number 8 (which has 4-th bit from right only turned on - 00001000).

If we invert it ~00001000 it becomes 11110111, then apply AND operator :

0000 1111 <----- val (159).
1111 0111 <----- ~mask (~8 = 11110111 = 0xF7).
___________

0000 0111.

Anshul said:   10 years ago
Please explain in detail?

Aba said:   9 years ago
What is f7 ?

Anonymous said:   9 years ago
I think the answer is wrong. Because they clearly mention that without disturbing any bit and why you guys are disturbing more than 1 bit?

In my point of view the answer is n = n & 16.

let us consider,

n is also 16.
So- 16 - ----> 1 0 0 0 0
& 1 0 0 0 0
-----------------------------------------
1 0 0 0 0

Here 4th bit is off and that also without disturbing any bit.

Post your comments here:

Your comments will be displayed after verification.