pta题目答案(非标准)
6-8 2.9 Getbits (5分)
write a function getbits(x,p,n) that returns the (right adjusted) n-bit field of x that begins at position p. We assume that bit position 0 is at the right end and that n and p are sensible positive values.
#include <stdio.h>
unsigned getbits(unsigned x, int p, int n);
void display(unsigned x);
int main()
{
unsigned x;
int p, n;
while(scanf("%u%d%d", &x, &p, &n) != EOF) {
display( getbits(x, p, n) );
}
return 0;
}
void display(unsigned x)
{
for(int i = 31; i >= 0; i--){
printf("%d",(x>>i)&1);
}
putchar('\n');
}
/* 请在这里填写答案 */
答案:
unsigned getbits(unsigned x, int p, int n){
return ((1<<n)-1)&(x>>(p-n+1));
}