The comment at the top was not followed because I printed the contents. I just want an opinion on coding style.
/*
* Write a function setbits(x,p,n,y) that returns x with the n bits
* that begin at position p set to the rightmost n bits of y, leaving
* the other bits unchanged in the least number of lines.
*
* Note: function signatures and curly brackets dont count towards
* the number of lines. You must also declare your variables, and
* call the function
*
* build with:
* gcc -o bit_twiddle -Wall -g -lm ./bit_twiddle.c
*/
#include <stdio.h>
#include <math.h>
#include <limits.h>
unsigned setbits(unsigned x, unsigned p, unsigned n, unsigned y) {
x |= (y & ~(~0 << n)) << p;
size_t s = (int)(log(INT_MAX)/log(2)) + 1;
printf("An int is %d bits\n", s);
int mask = pow(2.0, (int)s);
do {
((x & mask) == 0) ? printf("0") : printf("1");
((s%4)==0) ? printf(" ") : printf("");
x <<= 1;
} while (s--);
printf("\n");
}
void main( ) {
unsigned retrn=1, begin=3, nbits=3, input=7;
unsigned x = setbits(retrn, begin, nbits, input);
}
UPDATE
x |= (y & ~(0 << n)) << p --> x |= (y & ~(~0 << n)) << p
(0 << n)
– Loki Astari Nov 16 '11 at 2:59