现在的位置: 首页 > 综合 > 正文

C语言中位操作

2018年01月23日 ⁄ 综合 ⁄ 共 2097字 ⁄ 字号 评论关闭

一、基本位操作

<table border="0" cellspacing="0" cellpadding="2" width="402" unselectable="." "="" style="word-wrap: break-word; color: rgb(102, 102, 102); font-family: 宋体, Arial; font-size: 12px; line-height: 26px;">

|

&

~

取反

^

异或

<<

左移

>>

右移

二、位操作的常见用法

1.获取某位的值

  1. #define BitGet(Number,pos) ((Number)|= 1<<(pos)) //把某位置1 
  2. #define BitGet(Number,pos) ((Number) &= ~(1<<(pos)) //把某位置0
  3. #define BitGet(Number,pos) ((Number) >> (pos)&1)) //用宏得到某数的某位
  4. #define BitGet(Number,pos) ((Number) ^= 1<<(pos)) //把Number的POS位取反

2.设定某位的值(设为0或1)

方法一:

  1. #define setbit(x,y) x|=(1<<y) //将x的第y位置1 
  2. #define clrbit(x,y) x&=~(1<<y) //将x的第y位清0

方法二:

置0,用0去‘与’

int a|=(1<<x) // x就是某位需要置1的数字,如第四位置1为: a|=(1<<4)

置1,用1去‘或’ 

int a&=~(1<<x) //把某位置0

3.循环移位

  1. #define ROTATE_LEFT(x, n) ((x) << (n)) | ((x) >> ((* sizeof(x)) - (n))) 
  2. #define ROTATE_RIGHT(x, n) ((x) >> (n)) | ((x) << ((* sizeof(x)) - (n)))

4.计算绝对值

  1. int abs(int x) 
  2. { 
  3.     int y; 
  4.     y = x>>31; 
  5.     return (x^y)-y; //or:(x+y)^
  6. }
 5.判断整数的符号
  1. int sign(int x) 
  2. { 
  3.     return (x>>31)|(unsigned(-x))>>31;
  4. }
 6.两个数比较

  1.   x==y: ~(x-y|y-x) 
  2.   x!=y: x-y|y-
  3.   x<y:      (x-y)^((x^y)&((x-y)^x)) 
  4.   x<=y: (x|~y)&((x^y)|~(y-x)) 
  5.   x<y: (~x&y)|((~x|y)&(x-y))//无符号x,y比较 
  6.   x<=y: (~x|y)&((x^y)|~(y-x))//无符号x,y比较
7.交换两个数的值(swap)
  1. 1.x ^= y ; y ^= x ; x ^= y ;
  2. 2.x = x+y ; y = x-y ; x = x-y ;
  3. 3.x = x-y ; y = y+x ; x = y-x ;
  4. 4.x = y-x ; x = y-x ; x = x+y ;
8.位计数
  1. 方法一:
  2. int count(long v)
  3. {
  4.     int number = 0;
  5.  
  6.     while(v)
  7.     {
  8.         v &= (v-1);
  9.         number++;
  10.     }
  11.     return number;
  12. }
  13. 方法二:
  14. int count(unsigned x) 
  15. { 
  16.     x = x-((x>>1)&0x55555555) ; 
  17.     x = (x&0x33333333)+(x>>2)&0x33333333); 
  18.     x = (x+(x>>4))&0x0f0f0f0f; 
  19.     x = x+(x>>8); 
  20.     x = x+(x>>16); 
  21.     return x&0x0000003f; 
  22. }
 9.二进制和GRAY码的转换
  1. (1).二进制码到GRAY码的转换: 
  2.   unsigned B2G(unsigned B ) 
  3.   { 
  4.       return B ^ (B>>1) ; 
  5.   } 
  6.   (2).GRAY码到二进制码: 
  7.   unsigned G2B(unsigned G) 
  8.  {
  9.      unsigned B ; 
  10.      B = G ^ (G>>1) ; 
  11.      B = G ^ (G>>2) ; 
  12.      B = G ^ (G>>4) ; 
  13.      B = G ^ (G>>8) ; 
  14.      B = G ^ (G>>16) ; 
  15.      return B ;
  16.   }
10.位反转
  1. unsigned rev(unsigned x) 
  2. { 
  3.     x = (& 0x55555555) << 1 | (x>>1) & 0x55555555 ; 
  4.     x = (& 0x33333333) << 2 | (x>>2) & 0x33333333 ; 
  5.     x = (& 0x0f0f0f0f) << 4 | (x>>4) & 0x0f0f0f0f ; 
  6.     x = (x<<24) | ((x&0xff00)<<8) | ((x>>8) & 0xff00) | (x>>24) ; 
  7.     return x ;
  8. }

抱歉!评论已关闭.