Search code examples
c#if-statementevaluation

What does (id & 12) evaluate to?


I understand it is a simple question. Can anyone explain what the below 'if' does. Let's assume id = 0;

private bool item;

if (item = ((id & 12) == 12))
    ret = 1;
  1. Does (id & 12) evaluate to (0+12)? If yes, 12 == 12 becomes true.
  2. Does this check if item is equal to true?

Solution

  • & is the bitwise and operator. It keeps only those bits which are 1 in both operands.

    • 0 & 0 == 0
    • 0 & 1 == 0
    • 1 & 0 == 0
    • 1 & 1 == 1

    12 in binary is 1100 and 0 in binary is 0000, so 0 & 12 == 0.

    Which input gives you 12? Well, any input where bits 2 and 3 are set, so for example 1111 (15, 0xF), 1101 (13, 0xD), 1110 (14, 0xE), and of course 1100 (12, 0xC) itself. But many other inputs are possible, e.g. 11100 (28, 0x1C) or 11101 (29, 0x1D).

    Writing in hexadecmial notation is more compact and makes it easier to see if an input matches. 12 in hex is 0xC. Any other hexadecimal number with C, D, E, or F at the least significant position will satisfy your condition.

    Note that inputs such as 0101 (5) will fail the test, because 0101 & 1100 == 0100 (5 & 12 == 4).

    item is assigned the result of the bitwise and and this result is then used as a condition for your if statement.