Create a function to set integer by bit - C Function

C examples for Function:Utility Function

Description

Create a function to set integer by bit

Demo Code

#include <stdio.h>

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

int main(void)
{
    printf("%u\n", setbits(5555, 6, 3, 9567));
    return 0;// w  w w.  j ava  2s.c  om
}

int setbits(int x, int p, int n, int y){
    // xxxxx00000xxxxx
    unsigned a = x & ~(~(~0U << n) << (p + 1 - n));

    // 00000yyyyy00000
    unsigned b = (y & ~(~0U << n)) << (p + 1 - n);

    // xxxxxyyyyyxxxxx
    return a | b;
}

Related Tutorials