Solving exercise 2-6 setbits() from K&R (The C Programming Language, 2nd Edition) part 1
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
/* 2-6 Write a function setbits(x,p,n,y) that returns x with the n bits that | |
begin at position p set to the rightmost n bits of y, leaving the other bits | |
unchanged, page 49 */ | |
#include | |
unsigned setbits(unsigned x, int p, int n, unsigned y); | |
unsigned getbits(unsigned x, int p, int n); | |
int main() | |
{ | |
printf("%u\n", setbits(209, 4, 3, 187)); | |
} | |
/* getbits: get n bits from position p */ | |
unsigned getbits(unsigned x, int p, int n) | |
{ | |
return (x >> (p+1-n)) & ~(~0 << n); | |
} | |
/* setbits: replace bits p -> p+n of x with rightmost n bits from y */ | |
unsigned setbits(unsigned x, int p, int n, unsigned y) | |
{ | |
int bits, result; | |
bits = getbits(y, n-1, n); | |
/* result = ; */ | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment