khalfella

ansi_c_pg47_ch02_ex07.c

Nov 2nd, 2014
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.47 KB | None | 0 0
  1. /*
  2. * Exercise 2-7.
  3. * Write a function invert(x,p,n) that returns x with the n bits that begin at
  4. * position p inverted (i.e., 1 changed into 0 and vice versa), leaving the
  5. * others unchanged.
  6. */
  7.  
  8.  
  9. #include <stdio.h>
  10.  
  11.  
  12.  
  13. unsigned int
  14. invert(unsigned int x, int p, int n) {
  15. unsigned int mask = (~0 << (p+1-n)) ^ (~0<<(p+1));
  16. return x ^ mask;
  17. }
  18.  
  19. int
  20. main() {
  21. unsigned int x = 0xff;
  22. unsigned int y = 0x00;
  23. y = invert(x,2,1);
  24. printf ("y = %X \n", y);
  25. }
Advertisement
Add Comment
Please, Sign In to add comment