Help me figure out what this line does:
PORTX | = (1 & lt; & lt; 2);
PORTX & amp; = ~ (1 & lt; & lt; 2);
Well, I really can’t understand what it is | = or & amp; = ~ …
You can explain these lines with an example ….
Answer 1, authority 100%
PORTX | = (1 & lt; & lt; 2);
is shorthand for PORTX = PORTX | (1 & lt; & lt; 2);
PORTX & amp; = ~ (1 & lt; & lt; 2);
is shorthand for PORTX = PORTX & amp; ~ (1 & lt; & lt; 2);
now in parts:
& lt; & lt;
– bit shift operator . shifts the bits 2 to the left of 1. In general, this is 4, that is, (1 & lt; & lt; 2) == 4
.
~
is a bitwise NOT. roughly – inverts the bits.
|
is a bitwise OR. that is, an entry of the form PORTX = PORTX | 4;
sets the 2nd bit of PORTX to one.
& amp;
is a bitwise AND record of the form PORTX & amp; 4
“extracts” the 2nd bit from a number (that is, PORTX & amp; 4 == 0
when the 2nd bit is 0 and PORTX & amp; 4! = 0
when 2nd bit is 1)
Record of the form PORTX & amp; ~ 4
extracts all bits except the 2nd.
UPD: corrected about bitness. See 1 & lt; & lt; 2 is the same as 1 * 2 ^ 2 = 4. That is, in binary – 100b. Those. the second bit is set. Accordingly, it is the same with binary operations. When we apply PORTX & amp; 4
, then we leave the 2nd bit, and discard the rest. If we write PORTX | 2
then we will set the 1st bit.
P.S. in general, logically, the bits in a byte need to be numbered not from 1, but from 0. And then the post needs to be corrected again. 🙁
Answer 2, authority 53%
| =
is a bit assignment operator “or”, similar to
a | = b - & gt; a = a | b
~ bit inversion is an operation that changes all 0s to 1s and all 1s to 0.
& amp; = bit assignment operator “and”
a & amp; = b - & gt; a = a & amp; b