c - k&r exercise confusion with bit-operations -
the exercise is: write function setbits(x,p,n,y) returns x n bits begin @ position p set rightmost n bits of y, leaving other bits unchanged.
my attempt @ solution is:
#include <stdio.h> unsigned setbits(unsigned, int, int, unsigned); int main(void) { printf("%u\n", setbits(256, 4, 2, 255)); return 0; } unsigned setbits(unsigned x, int p, int n, unsigned y) { return (x >> (p + 1 - n)) | (1 << (n & y)); }
it's incorrect, on right path here? if not, doing wrong? i'm unsure why don't understand this, spent hour trying come this.
thanks.
here's algorithm:
- if n 0, return x.
- take 1, , left shift n times , subtract 1. call
mask
. - left shift mask p times call
mask2
. and
x inverse of mask2.and
y mask, , left shift p times.or
results of 2 operations, , return value.
Comments
Post a Comment