Skip to content

Instantly share code, notes, and snippets.

@shaobin0604
Created October 30, 2009 08:40
Show Gist options
  • Save shaobin0604/222224 to your computer and use it in GitHub Desktop.
Save shaobin0604/222224 to your computer and use it in GitHub Desktop.
/*
* Exercise 2-7. Write a function invert(x,p,n) that returns x with the n
* bits that begin at position p inverted (i.e., 1 changed into 0 and vice
* versa), leaving the others unchanged.
*/
#include <stdio.h>
unsigned int invert(unsigned int x, int p, int n);
unsigned int invert(unsigned int x, int p, int n) {
return (x & ~(~(~0 << n) << (p + 1 - n))) |
((~((x >> (p + 1 - n)) & ~(~0 << n)) & ~(~0 << n)) << (p + 1 - n));
}
int main(void)
{
unsigned int x = 0xc9;
unsigned int r = 0xc7;
int p = 3;
int n = 3;
if (r == invert(x, p, n))
printf("assert success!\n");
else
printf("assert fail!\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment