编写一个函数getbits,从一个16位的单元中取出某几位(即该几位保留原值,其余位为0)。函数的调用形式为 getbits(value,n1,n2);value为该16位(2个字节)中的数据值,n1为欲取出的起始位,n2为欲取出的结束位,例如getbits(0101675,5,8)表示对八进制101675这个数,取出它的从左面起第5位到第8位。
代码如下:
#include <stdio.h>
unsigned short int getbits(unsigned short value,int n1,int n2); int main(int argc,char *argv[]) { unsigned short int a; int n1,n2; printf("input an octal number:"); scanf("%o",&a); printf("input n1,n2:"); scanf("%d,%d",&n1,&n2); printf("result:%o\n",getbits(a,n1,n2)); system("pause"); return 0; } unsigned short int getbits(unsigned short value,int n1,int n2) { unsigned short int z; z = ~0; z = (z >> n1) & (z << (16-n2)); z = value & z; z = z >> (16 - n2); return z; }
|
阅读(5649) | 评论(0) | 转发(0) |