下面代码中bitget和bitset是bitrotleft中要用到的简单函数,功能分别是取得和设置指定位的bit值,我很难看懂bitrotleft函数,虽然书上简介写的很简单:轮转缓冲区bits(含size位),将位值向左移count位.此操作完成后,处于最左端的count位移动到缓冲区最右端,而且其他的位也相应的轮转.但是我在main函数的测试中好像并不如意,代码如下:#include#includeintbit_get(constunsignedchar*bits,intpos){unsignedcharmask;inti;/*设置掩码*/mask=0x80;for(i=0;i>1;/*获得当前位的数值*/return(((mask&bits[(int)(pos/8)])==mask)?1:0);}voidbit_set(unsignedchar*bits,intpos,intstate){unsignedmask;inti;mask=0x80;for(i=0;i>1;if(state)bits[pos/8]|=mask;elsebits[pos/8]&=(~mask);return;}voidbit_rot_left(unsignedchar*bits,intsize,intcount){intfbit,lbit,i,j;/*Rotatethebuffertotheleftthespecifiednumberofbits.*/if(size>0){for(j=0;j
2 回答
德玛西亚99
TA贡献1770条经验 获得超3个赞
测试程序应该这样写才对:intmain(){unsignedcharbits[3]={0x4b,0xdb,0};bit_rot_left(bits,16,2);printf("%#x,%#X,%#x",bits[0],bits[1],bits[2]);}输出是0x2f,0x6D,0
慕村9548890
TA贡献1884条经验 获得超4个赞
嗯你那个程序有错。。。我没有去调试它,不过我写了一个好用的:#include intgcd(inta,intb){returnb==0?a:gcd(b,a%b);}voidswap(unsignedchar*a,unsignedchar*b){unsignedchartmp=*a;*a=*b;*b=tmp;}voidrot1(unsignedchar*bits,intsize,intcount){intm=gcd(size,count),i,j;unsignedchartmp;count%=size;count=size-count;for(i=0;i{ tmp=bits[i];for(j=i+count;j!=i;j+=count){if(j>size)j-=size;swap(&tmp,bits+j);}bits[i]=tmp;}}voidrot2(unsignedchar*bits,intsize,intcount){inti;unsignedcharmask=~0<<(8-count),tmp1=0,tmp2;for(i=size-1;i>=0;i--){tmp2=(mask&bits[i])>>(8-count);bits[i]<<=count;bits[i]|=tmp1;tmp1=tmp2;}bits[size-1]|=tmp1;}voidbit_rot_left(unsignedchar*bits,intsize,intcount){rot1(bits,size,count/8);rot2(bits,size,count%8);}voidprint_bits(unsignedchar*bits,intsize){inti,j;for(i=0;ifor(j=0x80;j;j>>=1) printf("%d",!!(j&bits[i]));printf("\n");}intmain(){unsignedcharbits[]="10010101";print_bits(bits,8);bit_rot_left(bits,8,2);printf("%s\n",bits);print_bits(bits,8);return0;}输出如下0011000100110000001100000011000100110000001100010011000000110001????????1100010011000000110000001100010011000000110001001100000011000100
添加回答
举报
0/150
提交
取消