二进制补码运算公式:
-x = ~x + 1 = ~(x-1)
~x = -x-1 (逻辑非)
-(~x) = x+1
~(-x) = x-1
x+y = x - ~y - 1 = (x|y)+(x&y)
x-y = x + ~y + 1 = (x|~y)-(~x&y)
x^y = (x|y)-(x&y)
x|y = (x&~y)+y
x&y = (~x|y)-~x
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比较
在C#中我们可以这样交换两个数的值。从而不用我们常常使用的借助第三个变量来达到交换的目的
static void Swap(ref int a, ref int b)
{
a ^= b;
Console.WriteLine(a);
b ^= a;
Console.WriteLine(b);
a ^= b;
Console.WriteLine(a);
Console.WriteLine(b);
}
应用举例
(1) 判断int型变量a是奇数还是偶数
a&1 = 0 偶数
a&1 = 1 奇数
(2) 取int型变量a的第k位 (k=0,1,2……sizeof(int)),即a>>k&1
(3) 将int型变量a的第k位清0,即a=a&~(1<
static int average(int x, int y) //返回X,Y 的平均值
{
return (x&y)+((x^y)>>1);
}
(8)判断一个整数是不是2的幂,对于一个数 x >= 0,判断他是不是2的幂
static boolean power2(int x)
{
return ((x&(x-1))==0)&&(x!=0);
}
(9)计算绝对值
static int abs(int x)
{
int y;
y = x >> 31;
return (x ^ y) - y; //or: (x+y)^y
}
(10)取模运算转化成位运算 (在不产生溢出的情况下)
a % (2^n) 等价于 a & (2^n - 1)
(11)乘法运算转化成位运算 (在不产生溢出的情况下)
a * (2^n) 等价于 a<< n
(12)除法运算转化成位运算 (在不产生溢出的情况下)
a / (2^n) 等价于 a>> n
例: 12/8 == 12>>3
(13) a % 2 等价于 a & 1
(14) if (x == a) x= b;
else x= a;
等价于 x= a ^ b ^ x;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Wei
{
class Program
{
static void Main(string[] args)
{
//逻辑与
Console.WriteLine(8 & 9);
//逻辑或 结果是8
Console.WriteLine(8 | 9);
//逻辑非 结果是9
Console.WriteLine(~85);
//逻辑异或 结果是-86
Console.WriteLine(8 ^ 9);
/*
* 0000 1111
* 0111 1000
*/
//位左移 结果是120
Console.WriteLine(15 << 3);
/*
* 0000 1111
* 0000 0001
*/
//位右移 结果相当于是15/8
Console.WriteLine(15 >> 3);
Console.WriteLine("******************************");
int value1 = 1;
int value2 = 15;
Swap(ref value1, ref value2);
Console.WriteLine("交换后的值{0},{1}",value1,value2);
Console.WriteLine(abs(-25));
Console.ReadLine();
}
static void Swap(ref int a, ref int b)
{
a ^= b;
Console.WriteLine(a);
b ^= a;
Console.WriteLine(b);
a ^= b;
Console.WriteLine(a);
Console.WriteLine(b);
}
static int abs(int x)
{
int y;
y = x >> 31;
return (x ^ y) - y; //or: (x+y)^y
}
}
}