-4

If I want to set bit 2 of a value to 0, what's the difference between the two following:

value = value & (1<<2);
value = value & 0x2;
Brocodile
  • 67
  • 11

2 Answers2

4

When using a bitwise AND, you clear all bits not set in the mask. So you're actually only retaining one bit. If you only want to clear one, set all bits to 1 except the one you want. You can use the the ~ operator to invert all bits in your mask as follows:

value = value & ~(1<<2);
value = value & ~(0x2);

That said, These two statements clear different bits. In the first case , 1<<2 evaluates to 4, i.e. 00000100 or 0x04. In the second case, 0x2 is 00000010. Their inversions are 11111011 and 11111101 respectively.

dbush
  • 205,898
  • 23
  • 218
  • 273
1

Formal answer

Strictly speaking, if you are working with LSB then first form value = value & (1<<2);, which is equal to (pseudo, or using GNU extension, code that allows binary constants) value = value & 0b100; will set to 0 all bits except bit 2 and the second form value = value & 0x2; (or value = value & 0b10;) will set to 0 all bits except bit 1. So finally second form will do what you want - set to 0 bit 2 (together with many other bits, but who cares if we take your question exactly as it written?). Please note that if you are in MSB world than both of them will set to 0 bit 2

Informal answer

If, despite how you phrased you question, you actually wanted to know if there is difference between constant expression that uses shift operation and just constant literal then answer is no, there is no difference - compiler will evaluate expression (1<<2) as 4 at compile time

And how to correctly set just one bit to 0 is described in dbush's answer

mvidelgauz
  • 2,176
  • 1
  • 16
  • 23