K&R C Chapter 2 Exercise Solutions — Types, Operators, and Expressions

Chapter 2: Types, Operators, and Expressions covers C’s type system and operators in depth. The exercises focus on bitwise manipulation — rotating bits, setting and clearing fields, counting set bits — and type-conversion edge cases. Exercise 2-9 (x &= (x-1) deletes the rightmost 1-bit) is a classic bit-manipulation trick worth memorising. These are worked solutions …

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-3: htoi — Convert Hex String to Integer

Exercise 2-3. Write the function htoi(s), which converts a string of hexadecimal digits (including an optional 0x or 0X) into its equivalent integer value. The allowable digits are 0 through 9, a through f, and A through F. How htoi Works Hexadecimal is simply base-16 positional notation. Converting from a hex string to an integer …

K&R C Exercise 2-2: Loop Without && or ||

Exercise 2-2. Write a loop equivalent to the for loop below without using && or ||: for (i = 0; i < lim – 1 && (c = getchar()) != ‘\n’ && c != EOF; ++i) s[i] = c; Understanding the Problem The && operator in C is a short-circuit operator: if the left operand …