Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

C# And Bitwise Operator

This C# example program uses the bitwise and operator. It demonstrates how the bits change.

And Bitwise operator. The bitwise and operator changes bits.

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

Example. 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.


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()
	// Get two random values.
	var rand = new Random();
	int value1 = rand.Next();
	int value2 = rand.Next();

	// Use bitwise and operator.
	int and = value1 & value2;

	// Display bits.

    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';
		b[pos] = '0';
	return new string(b);



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.

Bitcount Algorithms

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.