# Explanation of function setbits

• 08-10-2012
sjmp
Explanation of function setbits
Can someone please provide me with a walk through of the function setbits return statements. And do you know why in the main function i is added to 511 and j is added to 37?

The code is a example from K&R Ch2-6

Code:

#include <stdio.h>

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

int main(void)
{
unsigned i;
unsigned j;
unsigned k;
int p;
int n;

for(i = 0; i < 30000; i += 511)
{
for(j = 0; j < 1000; j += 37)
{
for(p = 0; p < 16; p++)
{
for(n = 1; n <= p + 1; n++)
{
k = setbits(i, p, n, j);
printf("setbits(%u, %d, %d, %u) = %u\n", i, p, n, j, k);
}
}
}
}
return 0;
}

• 08-10-2012
std10093
The code you posted really needs to be edited :)
I do not know if you edited it or not but when i looked the whole code was just in one line.Might be fault of browser not loading fast enough
• 08-10-2012
std10093
Quote:

Originally Posted by sjmp
Can someone please provide me with a walk through of the function setbits return statements.

Check the bitwise operators C operators
• 08-10-2012
oogabooga
That doesn't look like K&R code to me. What version and page of the book is this from?
• 08-10-2012
std10093
Quote:

Originally Posted by oogabooga
That doesn't look like K&R code to me. What version and page of the book is this from?

I agree with oogabooga.I looked at my K&R book(2nd edition) at the chapter sjmp said but found nothing similar.
• 08-10-2012
oogabooga
Quote:

Originally Posted by std10093
I agree with oogabooga.I looked at my K&R book(2nd edition) at the chapter sjmp said but found nothing similar.

I just remembered that they often declared multiple variables on the same line (which is not done here) and left out unnecessary braces (again, not done here).

It also seems kind of pointless to be printing this all out (all 212976 lines of output). I.e., what's the point of it all? Surely if it's from a book, any book, the book would say.

It's more likely it's a programming puzzle. What does it do?
• 08-13-2012
sjmp
Sorry this was one of the examples for the reader to figure out

 6 49 "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."
• 08-14-2012
Click_here
OK, step 1 is to put values into the numbers
Write them out in binary:

x = 1100 0000
y = 0000 0011
p = 0000 0001
n = 0000 0001

(x & ((~0 << (p+1)) ...

(11000000 & ((~00000000 << (00000001 + 1)) ...
=(11000000 & ((11111111 << (00000010)) ...
=(11000000 & ((11111100))...
=(11000000 ...

You can see that this section of the logical statement allows you to clear p+1 bits from the right side of x

I don't want to spoil all your fun, so I'll let you work out the rest

:)