K&R C Exercise 2-9: Count Set Bits Using x &= (x-1)

K&R C Exercise 2-9 — Faster bitcount Using x &= (x-1) Exercise 2-9: In a two’s complement number system, x &= (x-1) deletes the rightmost 1-bit in x. Explain why. Use this observation to write a faster version of bitcount. Why Does x &= (x-1) Delete the Rightmost 1-Bit? This is the conceptual heart of …

K&R C Exercise 2-8: rightrot — Rotate Bits Right

K&R C Exercise 2-8 — rightrot(x, n) Exercise 2-8: Write a function rightrot(x,n) that returns the value of the integer x rotated to the right by n bit positions. Approach A right rotation is different from a right shift. When you shift right by n, the n bits that fall off the right end are …