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 …

K&R C Exercise 2-7: invert — Flip n Bits at Position p

K&R C Exercise 2-7 — invert(x, p, n) Exercise 2-7: Write a function invert(x,p,n) that returns x with the n bits that begin at position p inverted (i.e., 1 changed to 0 and vice versa), leaving the others unchanged. Approach XOR is the natural bit-flip operator: b ^ 1 = ~b and b ^ 0 …

K&R C Exercise 2-6: setbits — Set n Bits at Position p

K&R C Exercise 2-6 — setbits(x, p, n, y) Exercise 2-6: Write a function setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged. Approach K&R numbers bit positions from the right starting at 0, so bit 0 is …

K\&R C Exercise 2-5: any — Find First Matching Character

K and R C, Solution to Exercise 2-5: K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language, second addition, by Brian W.Keringhan and Dennis M.Ritchie(Prentice Hall,1988). You can learn and solve K&R C Programs Exercise.Write the C function any(s1, s2), which returns the first location in the …

K&R C Exercise 2-4: squeeze — Delete Characters from a String

Exercise 2-4. Write an alternative version of squeeze(s1,s2) that deletes each character in s1 that matches any character in the string s2. Approach The original K&R squeeze(s, c) removes all occurrences of a single character c from string s using a compact two-index pattern: index i scans every position in s, while index j only …