本文主要是介绍C语言中位操作,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、基本位操作
<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.获取某位的值
- #define BitGet(Number,pos) ((Number)|= 1<<(pos)) //把某位置1
- #define BitGet(Number,pos) ((Number) &= ~(1<<(pos)) //把某位置0
- #define BitGet(Number,pos) ((Number) >> (pos)&1)) //用宏得到某数的某位
- #define BitGet(Number,pos) ((Number) ^= 1<<(pos)) //把Number的POS位取反
2.设定某位的值(设为0或1)
方法一:
- #define setbit(x,y) x|=(1<<y) //将x的第y位置1
- #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.循环移位
- #define ROTATE_LEFT(x, n) ((x) << (n)) | ((x) >> ((8 * sizeof(x)) - (n)))
- #define ROTATE_RIGHT(x, n) ((x) >> (n)) | ((x) << ((8 * sizeof(x)) - (n)))
4.计算绝对值
- int abs(int x)
- {
- int y;
- y = x>>31;
- return (x^y)-y; //or:(x+y)^y
- }
5.判断整数的符号
- int sign(int x)
- {
- return (x>>31)|(unsigned(-x))>>31;
- }
6.两个数比较
- x==y: ~(x-y|y-x)
- x!=y: x-y|y-x
- x<y: (x-y)^((x^y)&((x-y)^x))
- x<=y: (x|~y)&((x^y)|~(y-x))
- x<y: (~x&y)|((~x|y)&(x-y))//无符号x,y比较
- x<=y: (~x|y)&((x^y)|~(y-x))//无符号x,y比较
7.交换两个数的值(swap)
- 1.x ^= y ; y ^= x ; x ^= y ;
- 2.x = x+y ; y = x-y ; x = x-y ;
- 3.x = x-y ; y = y+x ; x = y-x ;
- 4.x = y-x ; x = y-x ; x = x+y ;
8.位计数
- 方法一:
- int count(long v)
- {
- int number = 0;
-
- while(v)
- {
- v &= (v-1);
- number++;
- }
- return number;
- }
- 方法二:
- int count(unsigned x)
- {
- x = x-((x>>1)&0x55555555) ;
- x = (x&0x33333333)+(x>>2)&0x33333333);
- x = (x+(x>>4))&0x0f0f0f0f;
- x = x+(x>>8);
- x = x+(x>>16);
- return x&0x0000003f;
- }
9.二进制和GRAY码的转换
- (1).二进制码到GRAY码的转换:
- unsigned B2G(unsigned B )
- {
- return B ^ (B>>1) ;
- }
- (2).GRAY码到二进制码:
- unsigned G2B(unsigned G)
- {
- unsigned B ;
- B = G ^ (G>>1) ;
- B = G ^ (G>>2) ;
- B = G ^ (G>>4) ;
- B = G ^ (G>>8) ;
- B = G ^ (G>>16) ;
- return B ;
- }
10.位反转
- unsigned rev(unsigned x)
- {
- x = (x & 0x55555555) << 1 | (x>>1) & 0x55555555 ;
- x = (x & 0x33333333) << 2 | (x>>2) & 0x33333333 ;
- x = (x & 0x0f0f0f0f) << 4 | (x>>4) & 0x0f0f0f0f ;
- x = (x<<24) | ((x&0xff00)<<8) | ((x>>8) & 0xff00) | (x>>24) ;
- return x ;
- }
这篇关于C语言中位操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!