Check bits

I want to check two bits (for example, the number of bits 3 and 5) of uint8 values, if their value is 0, I want to return 1

uint8 a;
if ((a & !(1<<3)) && (a & !(1<<5)))
{
    Instructions..
}

Is this code correct?

+4
source share
7 answers

No, your code will not work the way you want. The operator !only displays 0or 1, and information about the actual non-zero bit is still lost. You can use something like this:

if(!(a & ((1 << 3) | (1 << 5))) {
    /* ... */
}

|. . &. 0, . 0 1 !, .

+4

.

! NOT, NOT.

, , 3 5 , :

uint8 a;
...
if (!(a & (1<<3)) && !(a & (1<<5)))
{
    Instructions..
}

if.

+1

, , . - , , . , , -.

, :

uint8_t mask = (1<<3) | (1<<5);

( , C , .)

:

if(data & mask) // if any bit contains value 1
  return 0;
else            // if no bit contains value 1
  return 1;

, , :

return !(data & mask);

:

bool check_bits (uint8_t data)
{
  uint8_t mask = (1<<3) | (1<<5);
  return !(data & mask);
}
+1

, a , , . ! ( ), . .

, ~, ~(1 << 3). , , , a .

, , !, !(a & 1 << 3).

0

, , , . :

(a & (1<<3)) + (a & (1<<5))

0, 0s.

0

. ! , 1<<3 , !(1<<3) . , a & !(1<<3) , .

, - , .

uint8 a;
/* assign something to a */
return (a & ((1 << 3) | (1 << 5))) == 0;

a & ((1 << 3) | (1 << 5)) - , 3- 5- (0-origin) a , . , , , , . == 1, 0 .

0

BIT_A BIT_B ( , ), :

#define BIT_A (1 << 3)
#define BIT_B (1 << 5)
...
#define BIT_Z (1 << Z)

...
/*      |here you put all bits           |here you put only the ones you want set */
/*      V                                V                                               */
if (a & (BIT_A | BIT_B | ... | BIT_Z) == (BIT_A | ... | BIT_I | ...))
{
    /* here you will know that bits BIT_A,..., BIT_I,... will **only**
     * be set in the mask of (BIT_A | BIT_B | ... | BIT_Z) */
} 

a & (BIT_A | BIT_B | ... ), , . , (, , , , ), , , .

, , , , . , , ( , ):

if (a & ((1 << 3) | (1 << 5)) == 0) { ...

( , , ). ( , ):

if (!(a & 0x28)) { /* 0x28 is the octal for 00101000, with the bits you require */

, ,

, ! , !(1<<3) 0 (1<<3 0, , 0) !(1<<5). , a & 0 ==> 0 a & 0 ==> 0, 0 && 0 ==> 0. , 0 -- false , a.

0

Source: https://habr.com/ru/post/1653878/


All Articles