Encoders
Hub for Computer Whizzes Register to join us

Encoders > More... > C > Program

/* A function that returns x with the n bits that begin at position p set
   to the rightmost n bits of y, leaving other bits unchanged. */

#include <stdio.h>

unsigned setbits(int x, int p, int n, int y);

main()
{
        printf("%d\n",setbits(116,5,4,58));
}

unsigned setbits(int x, int p, int n, int y)
{
        return x & ~(~(~0<<n) << p-n+1) | (y & ~(~0<<n)) << p-n+1;
}