SME
Embedded Systems · Problem type
Setting and clearing a register bit
Use this for “An 8-bit register holds 0x41. Set bit 3, then clear bit 6. What does it hold?”
Diagram
S = 0x41 | 0x08 = 0x49: bit 3 was 0, so it turns on and adds 2³ = 8.
C = 0x49 & 0xBF = 0x09: bit 6 was 1, so it turns off and takes away 2⁶ = 64.
Bits are numbered from 0 at the right; a lit bit is one the operation changed.
This is an example. Type your own values to start a new problem.
S
=
R
OR
(1
<<
k
)
C
=
S
AND
NOT
(1
<<
j
)
The picture writes OR as | and AND as &, the way C code does.
M
Set mask
worked out (not typed)
P
Bit j’s mask
worked out (not typed)
N
Clear mask
worked out (not typed)
Formulas
M
=
1
<<
k
0x08 = 1 << 3
S
=
R
OR
M
0x49 = 0x41 OR 0x08
P
=
1
<<
j
0x40 = 1 << 6
N
=
NOT
P
0xBF = NOT 0x40
C
=
S
AND
N
0x09 = 0x49 AND 0xBF
Assumptions
•
Bits are numbered from 0 at the right; the mask 1 << k is 2ᵏ, a 1 in bit k only.
•
OR with the mask sets bit k and leaves the others: a bit is 1 when either number has a 1 there.
•
AND with the inverted mask NOT (1 << j), written ~(1 << j) in C, clears bit j and keeps the rest.
Step-by-step
WE KNOW
R = 0x41, k = 3, j = 6
FIND
set mask (M), after setting (S), bit j’s mask (P), clear mask (N), after clearing (C)
Step 1 · Find set mask (M)
Use M = 1 << k
Shift
a
1
left
by
k
places:
a
1
in
bit
k
only.
1
<<
3
=
2
3
=
8
=
0,000
1,000₂
=
0x08
M
=
0x08
Step 2 · Find after setting (S)
Use S = R OR M
OR
bit
by
bit:
1
where
either
has
a
1,
so
bit
k
turns
on
and
the
rest
stay.
0x41 OR 0x08 = 0,100 0,001₂ OR 0,000 1,000₂ = 0,100 1,001₂ = 0x49
S
=
0x49
Step 3 · Find bit j’s mask (P)
Use P = 1 << j
Shift
a
1
left
by
j
places:
a
1
in
bit
j
only.
1
<<
6
=
2
6
=
64
=
0,100
0,000₂
=
0x40
P
=
0x40
Step 4 · Find clear mask (N)
Use N = NOT P
Invert
every
bit:
a
0
in
bit
j
and
1s
everywhere
else.
N
=
NOT
0x40
0x40 = 0,100 0,000₂
Invert every bit: 1,011 1,111₂
1,011 1,111₂ = 0xBF
N
=
0xBF
Step 5 · Find after clearing (C)
Use C = S AND N
AND
bit
by
bit:
1
only
where
both
have
a
1,
so
bit
j
turns
off
and
the
rest
stay.
0x49 AND 0xBF = 0,100 1,001₂ AND 1,011 1,111₂ = 0,000 1,001₂ = 0x09
C
=
0x09
Check
Put the numbers back in. Both sides should match.
0x08 = 1 << 3 ✓
0x49 = 0x41 OR 0x08 ✓
0x40 = 1 << 6 ✓
0xBF = NOT 0x40 ✓
0x09 = 0x49 AND 0xBF ✓
Topic check
See what you know: 5 questions on this topic
New questions each time. Pass to mark it complete.
Related lessons
Microcontrollers
Main lesson
A DAC’s output voltage
Use this for “An 8-bit DAC with a 5 V reference gets the code 200. What voltage comes out?”
An LED’s resistor on a pin
Use this for “A 3.3 V pin drives an LED with a 2 V drop at 10 mA. What resistor goes in series?”
A divider down to 3.3 V
Use this for “A 5 V signal reaches a 3.3 V pin through 2.2 kΩ over 3.3 kΩ. What voltage does the pin see?”