staticvoid Swap(refint a, refint b)
{
a ^= b;
Console.WriteLine(a);
b ^= a;
Console.WriteLine(b);
a ^= b;
Console.WriteLine(a);
Console.WriteLine(b);
}
staticintabs(int x)
{
int y;
y = x >> 31;
return (x ^ y) - y; //or: (x+y)^y
}
1
2
3
4
5
6
(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
{
staticvoid 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();
}
staticvoid Swap(refint a, refint b)
{
a ^= b;
Console.WriteLine(a);
b ^= a;
Console.WriteLine(b);
a ^= b;
Console.WriteLine(a);
Console.WriteLine(b);
}
staticint abs(int x)
{
int y;
y = x >> 31;
return (x ^ y) - y; //or: (x+y)^y
}
}
}原文链接http://blog.csdn.net/yy763496668/article/details/51627545点击打开链接