Created
May 18, 2020 09:33
-
-
Save sheilambadi/697a6f37df934d07f04bcc4dd6448f64 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.
This file contains 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
#include <stdio.h> | |
unsigned int invert(unsigned int x, int p, int n); | |
int main() | |
{ | |
unsigned int x; | |
unsigned int y; | |
unsigned int z; | |
x = 255; | |
y = invert(x, 0, 1); | |
z = invert(y, 0, 1); | |
fprintf(stdout, "x is %lu, inverted is %lu, inverted again is %lu\n", x, y, z); | |
x = 0xbc; | |
y = invert(x, 0, 1); | |
z = invert(y, 0, 1); | |
fprintf(stdout, "x is %lu, inverted is %lu, inverted again is %lu\n", x, y, z); | |
// add your own test cases - at least 4 more. | |
x = 255; | |
y = invert(x, 2, 2); | |
z = invert(y, 2, 2); | |
fprintf(stdout, "x is %lu, inverted is %lu, inverted again is %lu\n", x, y, z); | |
x = 255; | |
y = invert(x, 4, 3); | |
z = invert(y, 4, 3); | |
fprintf(stdout, "x is %lu, inverted is %lu, inverted again is %lu\n", x, y, z); | |
x = 255; | |
y = invert(x, 7, 8); | |
z = invert(y, 7, 8); | |
fprintf(stdout, "x is %lu, inverted is %lu, inverted again is %lu\n", x, y, z); | |
x = 0; | |
y = invert(x, 7, 8); | |
z = invert(y, 7, 8); | |
fprintf(stdout, "x is %lu, inverted is %lu, inverted again is %lu\n", x, y, z); | |
} | |
unsigned int invert(unsigned int x, int p, int n) | |
{ | |
// places zeros in the rightmost n bits and make mask with ones in the rightmost n bits | |
unsigned int mask = ((~(~0 << n))); | |
// n-bit field of x that begins at position p | |
unsigned int shift_no = p + 1 - n; | |
// shift mask so that field to be retained at correct position | |
unsigned int shifted_mask = (mask << shift_no); | |
// toggle original value so that only necessary values can change | |
return (x ^ shifted_mask); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment