C语言作为一种底层语言,常常需要用到位操作,对于初学者来讲,是一件让人头疼发的事情,本案例很好的解释了位操作的方法。
#include
#include
#include
int main(int argc, char *argv[]) {
char buf[3];
memset(buf,0,sizeof(buf));
int num;
int count;
memcpy(&num,buf,sizeof(buf));
printf(“字节变动之前:%d\n”,num);
memset(&buf[1],0xff,1);//设置buf的中间字节的位全都为1
printf(“这个字节的数字:%d\n”,(int)buf[1]);
memcpy(&num,buf,sizeof(buf));
printf(“%d\n”,0xff00);
printf(“%d\n”,num);
memset((void*)&num,0,sizeof(num));
memset((void*)&count,0,sizeof(num));
/*目前为止,符合想象*/
printf(“num = %d,count = %d\n”,(int)num,(int)count);
char up =0xf0;//11110000
char down = 0x0f;//00001111
char one = buf[1] & up;
char two = buf[1] & down;
char tmp[3];
memset(tmp,0,3);
memcpy(tmp,buf,3);
memcpy(&tmp[1],&one,1);
memcpy(&num,tmp,3);
memcpy(tmp,buf,3);
memcpy(&tmp[1],&two,1);
memcpy(&count,tmp,3);
printf(“位操作之后\n %d %d\n”,num,count);
return 0;
}
本文为原创文章,转载请注明出处!