1

How to check whether value is set or not

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

Here inside if I want to check whether Indicator have value 0x10 or not, Some case Indicator wil have value 0x10 and 0x04. I need to check 0x10 is ther eor not

4

5 回答 5

3

检查是否(Indicator & 0x10)等于0x10或否则。如果0x10非零则该位(或位)未设置,则该位被设置。这是因为&变量的意志和每一位,因此与0x10(或任何其他整数说MASK)进行与意味着如果在该与整数()的每个位置Indicator都有一个,结果将与与整数()相同。1MASKMASK

于 2013-08-06T09:25:44.927 回答
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)
{
  ...
}

也更容易理解发生了什么。

于 2013-08-06T09:43:49.133 回答
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)
于 2013-08-06T09:32:59.037 回答
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
于 2013-08-06T09:27:28.237 回答
0

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

如果设置了该位,则结果将为真,否则为假。

(Indicator & 0x10)
于 2013-08-06T10:56:26.043 回答