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:

  1. if n 0, return x.
  2. take 1, , left shift n times , subtract 1. call mask.
  3. left shift mask p times call mask2.
  4. and x inverse of mask2. and y mask, , left shift p times.
  5. or results of 2 operations, , return value.

Comments

Popular posts from this blog

unicode - Are email addresses allowed to contain non-alphanumeric characters? -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

c++ - Convert big endian to little endian when reading from a binary file -