Review:
How to
flip the bit at
position k
- The
FLIPBIT(x, k)
operation:
(flips the bit
at position
k in
x)
position k
|
V
Before FLIPBIT(x,k): x = 1010...?...1101
After FLIPBIT(x,k): x = 1010...¿...1101
|
- Solution:
apply an
XOR operation
to flip the
bit at
position k:
x = 1010...?...1101
pattern = 000..00100..000
---------------- XOR
x = 1010...¿...1101 (y XOR 0 = y and ? XOR 1 = ¿)
FLIPBIT(x,k) ≡ x = x ^ pattern
|
|
We have used a
shift operation
to
construct the
pattern
000..00100..000
before !!
Algorithm to
flip the bit at
position k
-
Recall
how to
construct the
pattern:
position k
|
V
pattern = 000..00100..000
|
- We start with
the following
binary pattern:
000....0....0001 (= 1 in decimal)
|
- Then
shift the
pattern
k positions
to the left:
000..00100..0000 (= 1 << k )
|
|
Algorithm to
flip the bit at
position k
- The
FLIPBIT(x, k)
operation:
(flips the bit
at position
k in
x)
position k
|
V
Before FLIPBIT(x,k): x = 1010...?...1101
After FLIPBIT(x,k): x = 1010...¿...1101
|
- Solution:
apply an
XOR operation
to flip the
bit at
position k:
x = 1010...?...1101
pattern = 000..00100..000 ≡ (1 << k)
---------------- XOR
x = 1010...¿...1101 (y XOR 0 = y and ? XOR 1 = ¿)
FLIPBIT(x,k) ≡ x = x ^ (1 << k)
|
|
Note:
C programmers
often
define
SETBIT as
a
macro:
#define FLIPBIT(x,k)
(x ^= (1 << k))
❮
❯