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));
}
本文介绍了一个实用的位操作函数getbits(x,p,n),该函数能够从整数x中获取指定位置p开始长度为n的比特位,并将其调整到右侧。通过具体的C语言实现代码示例,展示了如何使用位移和按位与操作来高效地解决问题。
1605

被折叠的 条评论
为什么被折叠?



