# C# And Bitwise Operator

Use the bitwise and operator: see how the bits change when it is used on an int.

And bitwise operator. The bitwise and operator changes bits. It provides important functionality for bitwise logic. When it is applied to 2 numbers, the result is another number that contains a 1 where each of the two numbers also have a 1.

To start, let's examine a program that generates two Random numbers. It then uses bitwise and on them. Next a helper method is invoked that loops through the bits in the numbers and writes them to the screen.Binary Representation
Note: The number that was returned contains a 1 in only the positions where the two operands (value1 and value2) also have ones.
C# program that uses bitwise and operator using System; class Program { static void Main() { int value1 = 555; int value2 = 7777; // Use bitwise and operator. int and = value1 & value2; // Display bits. Console.WriteLine(GetIntBinaryString(value1)); Console.WriteLine(GetIntBinaryString(value2)); Console.WriteLine(GetIntBinaryString(and)); } static string GetIntBinaryString(int value) { return Convert.ToString(value, 2).PadLeft(32, '0'); } } Output 00000000000000000000001000101011 00000000000000000001111001100001 00000000000000000000001000100001

Bitmasks. What are some realistic ways to use this operator? Often, data structures such as digital trees use bitmasks to store information. If you take two nodes in the tree, you can use the bitwise and to compare the data in their bitmasks.

If you use bitwise and, and the result is 0, then the two nodes contain no equal bits. Also, with the result of the bitwise and, you can use a bit counting function to determine just how many same bits the nodes have.Bitcounts
Tip: This sometimes leads to important performance improvements—particularly on large and complex data structures.

Summary. The bitwise and operator receives two parameters and returns a value that has a bit set to 1 where both of the operands also has a 1. This operator helps us understand how binary numbers are represented.
Also: It helps with data structures and algorithms where storage space must be compressed into bit masks.

Home

© 2007-2020 sam allen. send bug reports to info@dotnetperls.com.