【 求助 】关于位运算中的getbits
#include<stdio.h>unsigned getbits(unsigned value,int n1,int n2)
{
return (value >> n1) & ~( ~0 << (n2 - n1 + 1) );
}
void main()
{
unsigned 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));
}
我写的这个是从右边的位数开始的,我怎么都弄不出从左边位数开始的,还有我用的是VC++写c,我感觉这个跟VC有点关系,
getbits(101675,5,8) 返回 15;
getbits(101675,7,11) 返回 7;
我需要的结果是当getbits(101675,5,8)时,返回 7
我弄了个从左边位数开始的
#include<stdio.h>
unsigned short getbits(unsigned short value,int n1,int n2)
{
return ( value << ( n1 - 1 ) & ~ ( ~ 0 >> (n2 - n1 + 1) ) ) >> ( 15 - n2 + n1);
}
void main()
{
unsigned short 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));
}
结果还是
getbits(101675,5,8) 返回 15;
getbits(101675,7,11) 返回 7;
当把main中最后个printf改成getbits(a,15-n1,15-n2);
结果还是
getbits(101675,5,8) 返回 15;
getbits(101675,7,11) 返回 7;
真的无语了,那位大虾帮帮忙,先谢过!