
The bitwise and operator changes bits. It provides important functionality for bitwise logic. Each number is represented by a set of ones and zeros. When the bitwise and operator is applied to two numbers, the result is another number that contains a 1 where each of the two numbers also have a 1.
This C# example program uses the bitwise and operator. It demonstrates how the bits change.

To start, let's examine a program that generates two Random numbers, and then uses bitwise and on them. Then, a helper method is invoked that loops through the bits in the numbers and writes them to the screen. In the output, you can see how the number that was returned by the bitwise and operator contains a 1 in only the positions where the two operands (value1 and value2) also have ones.
Program that uses bitwise and operator [C#]
using System;
class Program
{
static void Main()
{
// Get two random values.
var rand = new Random();
int value1 = rand.Next();
int value2 = rand.Next();
// Use bitwise and.
int and = value1 & value2;
// Display bits.
Console.WriteLine(GetIntBinaryString(value1));
Console.WriteLine(GetIntBinaryString(value2));
Console.WriteLine(GetIntBinaryString(and));
}
static string GetIntBinaryString(int n)
{
// Displays bits.
char[] b = new char[32];
int pos = 31;
int i = 0;
while (i < 32)
{
if ((n & (1 << i)) != 0)
{
b[pos] = '1';
}
else
{
b[pos] = '0';
}
pos--;
i++;
}
return new string(b);
}
}
Output
00000111111010111110110011111010
01011100100101110101110010001001
00000100100000110100110010001000
What are some realistic ways that you can actually use a bitwise and in your programs? 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.
Bitcount Algorithms
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 not only helps us understand how binary numbers are represented, but can help certain data structures and algorithms where storage space must be compressed into bit masks; bitwise and can then compare these masks.
Bit Tips