Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Exercise 2-6.
- * 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.
- */
- #include <stdio.h>
- unsigned int
- setbits(unsigned int x, int p, int n, unsigned int y) {
- /*
- * The mask will have the bits to be changed set and others unset. It would
- * be easier if we are to generate this mask once and use it later on. Let
- * us make a simple convention first. The left bits are all the bits left
- * to the set bits. The set bits are the bits to be set by this function,
- * and the right bits are on the right of the set bits.
- *
- * The mask should eventually look like
- * 00000000000000000000000111111111111111111110000000000000000000000000
- * |-------left bits-----||---set bits (n)---||--right bits (p+1-n)---|
- *
- * In order to get this mask we have to XOR the below components.
- *
- * The first component (~0 << (p+1-n)), should give us the below
- * 11111111111111111111111111111111111111111110000000000000000000000000
- * |-------left bits-----||---set bits (n)---||--right bits (p+1-n)---|
- *
- * The second component (~0<<(p+1), should give us the below
- * 11111111111111111111111000000000000000000000000000000000000000000000
- * |-------left bits-----||---set bits (n)---||--right bits (p+1-n)---|
- */
- unsigned int mask = (~0 << (p+1-n)) ^ (~0<<(p+1));
- return (x&~mask)|((y<<(p+1-n))&mask);
- }
- int
- main() {
- unsigned int x = 0xff;
- unsigned int y = 0x00;
- y = setbits(x,2,1,y);
- printf ("y = %X \n", y);
- }
Advertisement
Add Comment
Please, Sign In to add comment