&=

From Microduino Wiki
Jump to: navigation, search

&=(Compound bitwise and )

Description
Compound bitwise and (&=) is usually used to set a certain bit of variables or constants as 0. In code, it is usually used to "clear" or "reset" a certain bit of a variable.


Syntax

x &= y;       // It is equal to x = x & y; 


Parameters
x: variable in char, int, or long-int y: constant in char, int, or long-int


For example
The first is the usage of bitwise and (&).

    0  0  1  1    operand 1
    0  1  0  1    operand 2
    ----------
    0  0  0  1    (operand 1 & operand 2) - the returned value 


After & with 0, all bits of any numbers will be cleared, if myByte is a variable.

myByte & B00000000 = 0;

After & with 1, all bits of any numbers won’t change, there is also a variable myByte.

myByte & B11111111 = myByte;

Note:Because we can use a bitwise operand to process the bitwise data, it is very convenient on the use of a binary constant. A binary number can be represented in other expressions, just difficult to understand. So, writing B00000000 in this way is to make it clearer, which is also representing "0".


So, if you want to set a certain bit of a variable as 0 or 1, and keep others unchanged, you can make it compound bitwise and (&=) with constant B11111100.

/*
   1  0  1  0  1  0  1  0    Variable  
   1  1  1  1  1  1  0  0    Mask
   ----------------------
   1  0  1  0  1  0  0  0    Returned value
  Number of unchanged bits.
                     The number of the bits is cleared. 
*/
  myByte =  10101010;
  myByte &= B1111100 == B10101000;


We replace the bit values on the variable with x, and you can see the result is same:

   x  x  x  x  x  x  x  x    variable
   1  1  1  1  1  1  0  0    mask
   ----------------------
   x  x  x  x  x  x  0  0
  Number of unchanged bits 
                     The number is cleared.

[Return to Arduino Syntax Manual]