代码改变世界

c#中位运算符的运用(转载)

2012-08-29 19:19  C#与.NET探索者  阅读(230)  评论(0编辑  收藏  举报
using System;
using System.Collections.Generic;
using System.Text;

namespace weiyunsuan
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 5;
            int y = 3;
            // & | ^ ~

            //&两个都是一才为1
            int z = x & y;
            //x=0101
            //y=0011
            //&-----------
            //z=0001(2)
            Console.WriteLine(z);

            //|两个有一个为一就为1
            z = x | y;
            //x=0101
            //y=0011
            //z=0111(7)
            Console.WriteLine(z);

            //^两个不同就为1
            z = x ^ y;
            //x=0101
            //y=0011
            //z=0110(6)
            Console.WriteLine(z);

            //~一元运算符相反值
            z = ~x;
            //x=0101
            //z=1010
            Console.WriteLine(z);

            z = x>>2;
            //x=0101
            //z=0001(1)
            Console.WriteLine(z);

            z = x << 2;
            //x=00010100
            //z=00010100
            Console.WriteLine(z);

            int x = 5;
            int y = 3;
            // & | ^ ~

            //&两个都是一才为1
            int z = x & y;
            //x=0101
            //y=0011
            //&-----------
            //z=0001(2)
            Console.WriteLine(z);

            //|两个有一个为一就为1
            z = x | y;
            //x=0101
            //y=0011
            //z=0111(7)
            Console.WriteLine(z);

            //^两个不同就为1
            z = x ^ y;
            //x=0101
            //y=0011
            //z=0110(6)
            Console.WriteLine(z);

            //~一元运算符相反值
            z = ~x;
            //x=0101
            //z=1010(-6)
            Console.WriteLine(z);


            z = x >> 2;
            //x=0101
            //z=0001(1)
            Console.WriteLine(z);

            z = x << 2;
            //x=00010100
            //z=00010100
            Console.WriteLine(z);

        }
    }
}