位检查验证

时间:2013-08-06 09:24:48

标签: c++ c bit-manipulation

如何检查是否设置了值

if (A)    Indicator |= 0x10;
if (B)    Indicator |= 0x04;
if(Indicator ) ??

如果我想检查指标是否具有值0x10,则在里面,某些情况指标将具有值0x100x04。我需要检查0x10是不是

5 个答案:

答案 0 :(得分:3)

检查(Indicator & 0x10)是否等于0x10或其他。如果0x10那么那个位(或位)如果非零则不被设置,那么该位被置位。这是因为&将和变量的每个位,因此与0x10(或任何其他整数说MASK)进行AND运算表示if Indicator1在该ANDed整数(MASK)的每个位置,结果将与ANDed整数(MASK)相同。

答案 1 :(得分:2)

您总是可以使用位字段而不是依赖幻数: -

struct Indicator
{
  unsigned int A_Set : 1;
  unsigned int B_Set : 1;
}

Indicator indicator;

if (A) indicator.A_Set = true;
if (B) indicator.B_Set = true;

if (indicator.A_Set)
{
  ...
}

理解正在发生的事情也更容易。

答案 2 :(得分:1)

你应该这样做:

if ( Indicator & 0x10 ) // if zero, the bit is not set if non-zero, the bit is set

您应该阅读:http://www.cprogramming.com/tutorial/bitwise_operators.html

示例:

(Indicator)    00100     // 0x04
 AND         & 10000     // 0x10
--------------------------------
             = 00000     // the bit is not set


(Indicator)    10000     // 0x10
 AND         & 10000     // 0x10
--------------------------------
             = 10000     // the bit is set


(Indicator)    10100     // 0x14
 AND         & 10000     // 0x10
--------------------------------
             = 10000     // the bit is set

答案 3 :(得分:1)

if (Indicator & 0x10) ; // A was true
if (Indicator & 0x04) ; // B was true

请注意,因为这里的两个值是单个位,所以您也不需要测试身份。

对于多位值,您可能需要它:

if (Indicator & 0x14) ; // at least one, and possibly both, of A and B were true
if ((Indicator & 0x14) == 0x14) ; // both A and B were true

当然:

if (Indicator == 0x10) ; // exactly A (ie, A but not B)

答案 4 :(得分:0)

你可以使用&运算符以查找该位是否已设置。

如果该位置位,则结果为true,否则为false。

(Indicator & 0x10)
相关问题