【问题标题】:What does (id & 12) evaluate to?What does (id & 12) evaluate to?
【发布时间】:2022-12-02 03:24:15
【问题描述】:

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?

【问题讨论】:

    标签: c# if-statement evaluation


    【解决方案1】:

    & is the bitwiseandoperator. 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), 1101 (13), 1110 (14), and of course 1100 (12) itself. But many other inputs are possible, e.g. 11100 (28).

    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.

    【讨论】:

      猜你喜欢
      • 2022-12-27
      • 2022-08-11
      • 2022-12-27
      • 2022-12-02
      • 2022-12-01
      • 2022-12-02
      • 1970-01-01
      • 2023-02-20
      • 2020-05-27
      相关资源
      最近更新 更多