=========================================== Exercise 2.6 - Setting bits at a position n =========================================== Question ======== 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. .. literalinclude:: cprogs/ex_2.6_setbits.c :language: c Explanation =========== The setbits function takes 4 inputs: - x: The original number we want to modify - p: The position where we want to make changes (counting from right, starting at 0) - n: How many bits we want to replace - y: The number we want to take bits from The function replaces n bits in x, starting at position p, with the rightmost n bits from y. :: setbits(0x37, 3, 2, 0x4E) // Returns 0x3B - x = 0x37 = 0011 0111 in binary - Starting at position 3 (p=3) - We want to change 2 bits (n=2) - Taking (2 ) bits from y = 0x4E = 0100 1110 The function: - Takes the rightmost 2 bits from y (10) - Places them at position 3 in x :: Original: 0011 0111 Result: 0011 1011 (0x3B) Visualization ============= .. raw:: html