Created
October 30, 2009 08:40
-
-
Save shaobin0604/222224 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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