| « Those who live in glass houses. . . | Blogging (and why Linux users should) » |
Sat, Jan 27, 2007
![[Icon]](rsc/img/chain_link.gif)
I swear, it takes longer to understand the question that in does the answer for these exercises.
In this case, you have to take 'n' bits from the binary value of 'x', beginning at position 'p'. Then set the rightmost bits of 'y' to those bits.
So if you have:
x = 14 = 001110
y = 13 = 001101
n = 3
p = 5
You want the '001' from x to be put at the end of y, to give 001001, which equals 9. The function I wrote does this, so I call it good. The annoying part was writing the main() function to actually test the setbits() function. So it goes. . .
Follow up:
int setbits(int x, int p, int n, int y)
{
/* Set the n bits beginning at p to be rightmost and zero all others */
x = (x >> (p+1-n)) & ~(~0 << n);
/* Zero the rightmost n bits of y */
y = y & (~0 << n);
/* Add the desired n bits of x to the zeroed n bits of y */
return x+y;
} ![[Links]](http://geekblog.oneandoneis2.org/skins/112/rsc/img/chain_link.gif)
Hmm.. new look for twitter? I hope it gets less "Ick! Change! Put it back!" nonsense than Facebook..
08/02/12
Facebook Syndication Error
11/02/12
![]()
I last listened to:
Johann Pachelbel - Canon in D major
Most recent photo:
Submersible houseboat