C语言_常见位操作
文章目录
- C语言_常见位操作
- 一、位操作函数
- 二、代码示例
一、位操作函数
设置某位为1或者对某位清0、获取某位的值、对某位取反
/*对某位置1*/
unsigned Setbit(unsigned x,int n)
{return x |= 1 << n;
}/*对某位清0*/
unsigned Resetbit(unsigned x,int n)
{return x &= ~(1 << n);
}/*取某位的值*/
unsigned Getbit(unsigned x,int n)
{return ((x) >> (n)&1))
}/*对某位取反*/
unsigned Invertbit(unsigned x,int n)
{return ((x) ^= 1<<(n))
}
获取x从p位到n位的值
unsigned Getbits(unsigned x,int p,int n)
{return (x >> (p+1-n)) & ~(~0 << n);
}
设置x从p位到n位的值
unsigned Setbits(unsigned x,int p,int n,int y)
{return x & ~(~(~0 << n) << (p+1-n)) | (y & ~(~0 << n)) << (p+1-n);
}
对x从p位到n位的值进行取反
unsigned Invertbits(unsigned x,int p,int n)
{return x ^ (~(~0 << n)) << (p-n+1);
}
对x循环右移n位
unsigned Rightbits(unsigned x,int n)
{return (x >> n) | (x << (8*(sizeof(unsigned))-n));
}
二、代码示例
代码如下(示例):
#include<stdio.h>
#include<string.h>void print_binary(unsigned int num) {if (num > 1) {print_binary(num >> 1);}putchar((num & 1) ? '1' : '0');}/*对某位置1*/
unsigned Setbit(unsigned x,int n)
{return x |= 1 << n;
}/*对某位清0*/
unsigned Resetbit(unsigned x,int n)
{return x &= ~(1 << n);
}/*取某位的值*/
unsigned Getbit(unsigned x,int n)
{return ((x) >> (n)&1);
}/*对某位取反*/
unsigned Invertbit(unsigned x,int n)
{return ((x) ^= 1<<(n));
}unsigned Getbits(unsigned x,int p,int n)
{return (x >> (p+1-n)) & ~(~0 << n);
}unsigned Setbits(unsigned x,int p,int n,int y)
{return x & ~(~(~0 << n) << (p+1-n)) | (y & ~(~0 << n)) << (p+1-n);
}unsigned Invertbits(unsigned x,int p,int n)
{return x ^ (~(~0 << n)) << (p-n+1);
}unsigned Rightbits(unsigned x,int n)
{return (x >> n) | (x << (8*(sizeof(unsigned))-n));
}void main(int argc,char* argv[])
{int a= 178 ,b= 178 , c= 178 , d= 178 , e= 178 , f= 178 , g= 178 , h = 178; int p = 5,n = 3;printf(" 178: \t\t\t");print_binary(a);printf("\t\n\n");printf(" Setbit(a,3): \t\t");print_binary(Setbit(a,3));printf("\t\n");printf(" Resetbit(b,4): \t");print_binary(Resetbit(b,4));printf("\t\n");printf(" Getbit(c,5):\t\t");print_binary(Getbit(c,5));printf("\t\n");printf(" Invertbit(d,2):\t");print_binary(Invertbit(d,2));printf("\t\n");printf(" Getbits(e,5,3):\t");print_binary(Getbits(e,5,3));printf("\t\n");printf(" Setbits(f,p,n,15):\t");print_binary(Setbits(f,p,n,15));printf("\t\n");printf(" Invertbits(g,5,3):\t");print_binary(Invertbits(g,5,3));printf("\t\n");printf(" Rightbits(h,5):\t");print_binary(Rightbits(h,5));printf("\t\n");}
结果:
178: 10110010
Setbit(a,3): 10111010
Resetbit(b,4): 10100010
Getbit(c,5): 1
Invertbit(d,2): 10110110
Getbits(e,5,3): 110
Setbits(f,p,n,15): 10111010
Invertbits(g,5,3): 10001010
Rightbits(h,5): 10010000000000000000000000000101