数据压缩位操作中的一个函数bit_rot_left "位向左轮转"看不懂,望指点

下面代码中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;
else
bits[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
芜湖不芜
浏览 705回答 2
2回答

德玛西亚99

测试程序应该这样写才对: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

嗯你那个程序有错。。。我没有去调试它,不过我写了一个好用的:#includeintgcd(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;isize)j-=size;swap(&tmp,bits+j);}bits[i]=tmp;}}voidrot2(unsignedchar*bits,intsize,intcount){inti;unsignedcharmask=~0>(8-count);bits[i]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript