Write a function
setbits(x,p,n,y)
that returnsx
with then
bits that begin at positionp
set to the rightmostn
bits ofy
, leaving the other bits unchanged.
This one took about a week to wrap my head around bitwise operations. It was quite confusing in the beginning, however as I had a look at it everyday, it started becoming more intuitive, until the solution became obvious
The idea is:
- replace the first number
x
field of lengthn
at positionp
with just zeros - mask out only the field of length
n
of the second numbery
and move it to positionp
- combine both numbers using the or operator
|
So for instance
x = 255
which is1111 1111
in binary- then we say from position
p = 5
for length ofn = 4
replace with 0's which is1100 0011
in binary - then grab the second number
y = 85
which is01010101
in binary - mask out only the field of
n
and move over into positionp
which is0001 0100
in binary - finally, combine both numbers
1100 0011
and0001 0100
using|
- final answer is
1101 0111
#include <stdio.h>
unsigned int setbits(unsigned int x, unsigned int p, unsigned int n, unsigned int y);
int main(void) {
unsigned int x = 128;
unsigned int p = 3;
unsigned int n = 2;
unsigned int y = 3;
printf("x: %d\np: %d\nn: %d\ny: %d\n\n", x, p, n, y);
printf("Result: %d\n\n", setbits(x, p, n, y));
x = 255; p = 5; n = 6; y = 85;
printf("x: %d\np: %d\nn: %d\ny: %d\n\n", x, p, n, y);
printf("Result: %d\n", setbits(x, p, n, y));
return 0;
}
unsigned int setbits(unsigned int x, unsigned int p, unsigned int n, unsigned int y) {
unsigned int old = x & ~(~(~0 << n) << (p + 1 - n)); /* replace field for replacement with 0's */
unsigned int new = (y & ~(~0 << n)) << (p + 1 - n); /* get only rightmost field and bitshift into position */
printf("Old: %d\nNew: %d\n", old, new);
return old | new; /* combine old and new */
}