Bit operations in C #

Source: Internet
Author: User
Tags bitwise bitwise operators

Bitwise operators are operators that perform operations on data by bits. Bit operations are operations supported by many other languages, such as C, C + +, and Java, and C # is no exception to support bit operations. Note bit operations support data types that are basic data types, such as Byte, short, char, int, long, and so on, C # supports bit operations as follows:

By Bit and &

by bit or |

Take the counter by the position

Move left <<

Move Right >>

Different or ^

In C #, bit operations are no different from C's bitwise operations, bit operation is relatively fast, and if skilled, it is relatively convenient to handle, especially in some permissions and other related settings, such as: 1, 2, 4, 8, 16, 32, 64, respectively, to view, add, edit, modify, delete, Permission values such as approval, if a user's final permission is the superposition of multiple rights values, using a bit operation to determine whether a certain kind of authority is quite convenient.

An example is provided:

Using System;

public class Bitaction

{

public static void Main (string[] args)

{

int[] Power = new int[] {1, 2, 4, 8, 16, 32, 64};

int value = 126;

/*

* 1 binary form: 00000001

* 2 binary form: 00000010

* 4 binary form: 00000100

* 8 binary form: 00001000

* 16 binary form: 00010000

* 32 binary form: 00100000

* 64 binary form: 01000000

* 126 binary form: 01111110

*/

for (int i = 0; i < power. Length; i++)

{

if ((Value & Power[i])!= 0)

{

Console.WriteLine ("Have power[{0}]={1}", I, power[i]);

}

}

Console.WriteLine ("Bitwise AND: 126&4={0}", Value & 4);

Console.WriteLine ("Bitwise OR: 126|4={0}", value | 4);

Console.WriteLine ("Move Left: 126<<4={0}", Value << 4);

Console.WriteLine ("Move Right: 126>>4={0}", Value >> 4);

Console.WriteLine ("Xor or: 126^4={0}", value ^ 4);

Console.WriteLine ("Bitwise Counter: ~126={0}", ~value);

Console.ReadLine ();

}

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.