www.
linuxforu.
com | LINUX FOR YOU | APRIL 2007
C M Y K
73
It is assumed that the underlying implementation follows
2’s complement representation for integers.
Assume that i, j and r are integers.
Q1: What does the expression “(i & (i – 1))” do?
A: It...
More
www.
linuxforu.
com | LINUX FOR YOU | APRIL 2007
C M Y K
73
It is assumed that the underlying implementation follows
2’s complement representation for integers.
Assume that i, j and r are integers.
Q1: What does the expression “(i & (i – 1))” do?
A: It checks if i is a power of 2 or not!
Q2: What does the expression (i & (-i)) do?
A: It returns the lowest bit set in an integer (which is a
power of 2)!
Q3: How can you express ~i in terms of other (preferably
bit-wise) operators?
A: (i ^ (~0)) and –(i + 1).
Q4: What does the expression (j + ((i - j) & -(i < j)) do?
A: This code results in the maximum of two integers i
and j.
Q5: How can you express the expression (i + j) in terms
of bit-wise ‘&’ and ‘|’ operations?
A: ((i & j) + (i | j))
Q6: What is the significance of the expression r = (i ^ j ^
r)?
A: If r is equal to i, r will be reset to j; else if r is equal to
j, r will be reset to i!
That’s enough; let’s see the explanation.
Q1.
When i is a value that’s a power of 2, only a
Less