alexexcl (24) Hello, I am trying to write a C program that uses 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. I am almost sure that I have the return function x in setbits() is correct. since I got the first output correct. I am confused on why my other three outputs are incorrect, can someone please tell me why or modify my code / setbits() function to get the Desired Output? Desired Output: setbits(x=0x1234, p=15, n=8, y=0xffff) => 0xff34 setbits(x=0x1234, p=14, n=3, y=0x2) => 0x2234 setbits(x=0x1234, p=20, n=6, y=0xf2) => 0x191234 setbits(x=0x1234, p=31, n=4, y=0x192f) => 0xf0001234 Actual Output: setbits(x=0x1234, p=15, n=8, y=0xffff) => 0xff34 setbits(x=0x1234, p=14, n=3, y=0x2) => 0x234 setbits(x=0x1234, p=20, n=6, y=0xf2) => 0x1234 setbits(x=0x1234, p=31, n=4, y=0x192f) => 0x1234 The C Code I have is below:
Duthomhas (13206) Extra tricky code makes extra tricky errors. Break it down. You need two masks, one for the N bits starting at xp, and one for the N LSB bits of y. It is also useful to put that shift expression as a variable. Also, I added a test case.