linux2021
contributed by < Billy4195
>
get_middle()
uses two pointer fast
and slow
to traverse the linked-list try to get the middle element. The algorithm is that the fast
pointer move two-step(two elements) in each iteration. When it reach the end of the list, the middle element is pointed by the slow
pointer.
So the end condition for the traverse is when the fast
pointer reach the end of the linked-list.
COND1 = ?
(c) fast->next == list
COND2 = ?
(b) fast->next->next == list
MMM = ?
(e) &get_middle(&q->list)->list
TTT = ?
(a) slow
The func
receive an 16bits unsigned int N, it will return an number which is power of 2 and less than or equal to N
At the first glance, it's hard to understand how it works. However, I guess the answers of X
, Y
, Z
may have something to do with power of 2.
I write a simple program to test the behavior of this function, and fill the X
, Y
and Z
with 2, 4, 8, respectively.
The program works as expected so far, and we need to understand what it did.
If the given N
for the func
is 7, the binary expression is 0000111
After Line 7 executed (N |= N >> 1
), N
is still 7. After Line 7-10 is executed, the N remains 7
.
The finaly statement add 1 to N (N=8 00001000
), and right shift 1 bit will be 4 (00000100
).
The binary expression of 26 is 00011010
N |= N >> 1
N =
00011111
= 31
N |= N >> 2
N =
00011111
= 31
N |= N >> 4
N =
00011111
= 31
N |= N >> 8
N =
00011111
= 31
(N+1) >> 1
N =
00001000
= 16
According above two cases, I guess the func
will fill all the bits on the right hand side of the leading 1
bit with 1
, and the add 1 to make it be an number is power of 2 and larger than N
. Then the right shift 1 bit to make it to be an power of 2 and less than or equal to N.
To prove my guessing is correct, I take a simplified case for uint8.
The func
will become as follows:
For the given N is 128
TODO: Explain implementation
TODO: Add more complex test cases
Discuss the case of N = MAX_UINT16 or 0
X = ?
(b) 2
Y = ?
(d) 4
Z = ?
(h) 8
RRR = ?
(a) data <<= read_lhs
For line 43-47, data
will store the first 1 bytes data from source
.
If read_lhs == 0
, then data
is just the same as source
If read_lhs > 0
, we need to eliminate the bits of left hand side.
Therefore, RRR
should be (a)
which left shift read_lhs
bits to make the extra bits of source to be deleted.
DDD = ?
(b) mask |= write_mask[write_lhs + bitsize]
CCC = ?
โโโโ(a) strlen(str) + 1
โโโโ(b) strlen(str) * 2
โโโโ(c) s->hash_size
โโโโ(d) s->size
โโโโ(e) strlen(s->cstr) + 1