【问题标题】:"Bit-masking” condition is not returning correct value“位掩码”条件未返回正确值
【发布时间】:2019-08-24 07:38:16
【问题描述】:

位掩码没有返回正确的值

我正在尝试解决这种情况,但我总是得到 8 作为返回值。我不确定读取位操作的条件。

int outputbyte[3] = {10,11,12};
int result;
result = (outputbyte[1] & 11)?8:0;
printf("\nMasked value is: %d", result);

我不明白这个条件是如何变成真的(outputbyte[1] & 11)?

【问题讨论】:

  • 你认为11&11 是假的吗?

标签: c bitwise-operators data-masking


【解决方案1】:

这里

int outputbyte[3] = {10,11,12};
result = (outputbyte[1] & 11)?8:0;

这个

result = (outputbyte[1] & 11)?8:0  /* (outputbyte[1] & 11) results in true hence 8 assigned to result */

是三元运算符,即第一个 operand-1(outputbyte[1] & 11)?8:0) 被评估,如果它导致 非零,则 operand-28 被分配给 result 否则 operand-30 被分配给 result

outputbyte[1] ==> 11   => 0000 1011
                                  & ( bitwise AND operator)
                  11   => 0000 1011
                         -----------
                          0000 1011   => 11 i.e nonzero i.e condition true i.e 11 gets assigned to result
                         -----------

我希望你知道按位 AND & 运算符的真值表是

A   B    A&B
------------
0   0     0
0   1     0
1   0     0
1   1     1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    • 1970-01-01
    • 2019-11-01
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多