Could you suggest ways of making this more simple?
/*
* Next write a function invert(x,p,n) that returns x with the n bits
* that begin at position p inverted, leaving the others unchange
*/
void printbits(unsigned x) {
size_t size_of_int = sizeof(int) << 3;
unsigned mask = 1;
int i = 0;
for(i = 1; i <= size_of_int; ++i, x >>= 1) {
((x & mask) == 0) ? printf("0") : printf("1");
((i & 3)==0) ? printf(" ") : printf("%s","");
}
printf("\n");
}
void invert(unsigned x, unsigned p, unsigned n) {
printbits(((~((((~(~0 << n) << p))) & x)) & (~(~0 << n) << p)) | (x & ~(~(~0 << n) << p)));
}
int main(int argc, char *argv[]) {
unsigned input=3082676239, begin=15, nbits=5;
invert(input, begin, nbits);
return(0);
}
Before mushing the parts together this is what I get in output:
x = 1111 0000 0001 0111 1011 1101 1110 1101 =================================================================== mask0 = 1111 0000 0001 0110 0000 1101 1110 1101 mask1 = 1111 1111 1111 1110 0100 1111 1111 1111 mask2 = 0000 0000 0000 0001 1111 0000 0000 0000 =================================================================== output = 1111 0000 0001 0110 0100 1101 1110 1101