khalfella

ansi_c_pg47_ch02_ex06.c

Nov 2nd, 2014
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. /*
  2. * Exercise 2-6.
  3. * Write a function setbits(x,p,n,y) that returns x with the n bits that begin
  4. * at position p set to the rightmost n bits of y, leaving the other bits
  5. * unchanged.
  6. */
  7.  
  8.  
  9. #include <stdio.h>
  10.  
  11.  
  12.  
  13. unsigned int
  14. setbits(unsigned int x, int p, int n, unsigned int y) {
  15.  
  16. /*
  17. * The mask will have the bits to be changed set and others unset. It would
  18. * be easier if we are to generate this mask once and use it later on. Let
  19. * us make a simple convention first. The left bits are all the bits left
  20. * to the set bits. The set bits are the bits to be set by this function,
  21. * and the right bits are on the right of the set bits.
  22. *
  23. * The mask should eventually look like
  24. * 00000000000000000000000111111111111111111110000000000000000000000000
  25. * |-------left bits-----||---set bits (n)---||--right bits (p+1-n)---|
  26. *
  27. * In order to get this mask we have to XOR the below components.
  28. *
  29. * The first component (~0 << (p+1-n)), should give us the below
  30. * 11111111111111111111111111111111111111111110000000000000000000000000
  31. * |-------left bits-----||---set bits (n)---||--right bits (p+1-n)---|
  32. *
  33. * The second component (~0<<(p+1), should give us the below
  34. * 11111111111111111111111000000000000000000000000000000000000000000000
  35. * |-------left bits-----||---set bits (n)---||--right bits (p+1-n)---|
  36. */
  37.  
  38.  
  39. unsigned int mask = (~0 << (p+1-n)) ^ (~0<<(p+1));
  40. return (x&~mask)|((y<<(p+1-n))&mask);
  41. }
  42.  
  43. int
  44. main() {
  45. unsigned int x = 0xff;
  46. unsigned int y = 0x00;
  47. y = setbits(x,2,1,y);
  48. printf ("y = %X \n", y);
  49. }
Advertisement
Add Comment
Please, Sign In to add comment