And Bitwise OperatorUse the bitwise and operator: see how the bits change when it is used on an int.
C#
And bitwise operator. The bitwise "and" operator changes bits. It provides important functionality for bitwise logic. We can use it to determine if 2 values have similar bits.
This operator is applied to 2 numbers. The result is another number that contains a 1 where each of the two numbers also have a 1.
Input and output. We pass 2 numbers to AND. The result in another number (usually an int). The appropriate bits are set according to the logic rules.
Operand: 011 Operand: 001 Result: 001
Example. This program generates 2 random numbers. It then uses bitwise "and" on them. Next a helper method is invoked, and we write the bit values to the screen.
Note The number that was returned contains a 1 in only the positions where the two operands (value1 and value2) also have ones.
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'); } }
00000000000000000000001000101011 00000000000000000001111001100001 00000000000000000000001000100001
Bitmasks. Data structures such as digital trees use bitmasks to store information. If you take 2 nodes in the tree, you can use the bitwise and to compare the data in their bitmasks.
Result If the result is 0, the nodes contain no equal bits. A bit counting function can determine how many same bits the nodes have.
Bitcounts
Tip This sometimes leads to important performance improvements—particularly on large and complex data structures.
A 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.
Final notes. This operator helps us understand how binary numbers are represented. It helps with data structures and algorithms where storage space must be compressed into bit masks.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.