zoukankan      html  css  js  c++  java
  • 位操作

    位操作符是对数据按二进制位进行运算的操作符。位操作是其他很多语言都支持的操作,如C、C++和Java等,C#也不例外支持位操作。注意位操作支持的数据类型是基本数据类型,如byte、short、char、int、long等,C#支持的位操作有如下几种:
    · 按位与 & 
    · 按位或 | 
    · 按位取反 ~ 
    · 左移 << 
    · 右移 >>
    · 异或^

    在C#中位操作同C的位操作没有什么却别,位操作的速度相对较快,而且如果熟练的话,处理起来也相对方便,特别是在一些权限等相关的设置中,比如:用1、2、4、8、16、32、64分别代表查看、添加、编辑、修改、删除、审批等权限值的时候,如果某个用户的最终权限是多种权限值的叠加,用位操作来判断是否具有某种权限是相当方便的了。

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.ServiceProcess;
    using System.Text;
    
    namespace AllDemo
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                int[] power = new int[] { 1, 2, 4, 8, 16, 32, 64 };
                int value = 126;
                /*
                 * 1的二进制形式:  00000001
                 * 2的二进制形式:  00000010
                 * 4的二进制形式:  00000100
                 * 8的二进制形式:  00001000
                 * 16的二进制形式: 00010000
                 * 32的二进制形式: 00100000
                 * 64的二进制形式: 01000000
                 * 126的二进制形式:01111110
                 */
                for (int i = 0; i < power.Length; i++)
                {
                    if ((value & power[i]) != 0)
                    {
                        Console.WriteLine("有power[{0}]={1}所代表的权限", i, power[i]);
                    }
                }
                Console.WriteLine("按位与:126&4={0}", value & 4);
                Console.WriteLine("按位或:126|4={0}", value | 4);
                Console.WriteLine("左移:126<<4={0}", value << 4);
                Console.WriteLine("右移:126>>4={0}", value & 4);
                Console.WriteLine("异或:126^4={0}", value ^ 4);
                Console.WriteLine("按位取反:~126={0}", ~value);
                Console.ReadLine();
            }
        }
    }
    View Code
  • 相关阅读:
    yii2.0安装redis
    composer
    Windows下安装redis
    Windows下启动redis闪退
    svn的使用及安装
    mysql主从
    linux下远程链接mysql报错1045
    git命令行克隆报错fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.
    git克隆报错128
    yii phpexcel <转>
  • 原文地址:https://www.cnblogs.com/scmail81/p/8683289.html
Copyright © 2011-2022 走看看