下面代码中bitget和bitset是bitrotleft中要用到的简单函数,功能分别是取得和设置指定位的bit值,我很难看懂bitrotleft函数,虽然书上简介写的很简单:轮转缓冲区bits(含size位),将位值向左移count位.此操作完成后,处于最左端的count位移动到缓冲区最右端,而且其他的位也相应的轮转.但是我在main函数的测试中好像并不如意,代码如下:#include #include intbit_get(constunsignedchar*bits,intpos){unsignedcharmask;inti;/*设置掩码*/mask=0x80;for(i=0;i<(pos%8);i++)mask=mask>>1;/*获得当前位的数值*/return(((mask&bits[(int)(pos/8)])==mask)?1:0);}voidbit_set(unsignedchar*bits,intpos,intstate){unsignedmask;inti;mask=0x80;for(i=0;i<(pos%8);i++)mask=mask>>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{ for(i=0;i<=((size-1)/8);i++){/*Getthebieabouttobeshiftedoffthecurrentbyte.*/lbit=bit_get(&bits[i],0);if(i==0)/*Savethebitshiftedoffthefirstbyteforlater.*/fbit=lbit;else/*Settherightmostbitofthepreviousbytetotheleftmostbitabouttobeshiftedoffthecurrentbyte.*/bit_set(&bits[i-1],7,lbit);/*Settherightmostbitofthebuffertothebitshiftedoffthefirstbyte.*/bits[i]=bits[i]<<1;}bit_set(bits,size-1,fbit);}}return;}intmain(){unsignedcharbits[]="10010101";bit_rot_left(bits,8,2);printf("%s\n",bits);}输出如下?010101
德玛西亚99
慕村9548890
相关分类