bitwise AND

In this chapter you will learn:

  1. Using bitwise AND
  2. Use bitwise AND to make a number even
  3. Use bitwise AND to determine if a number is odd.

Using bitwise AND

class MainClass/*from j  av  a 2s.  co  m*/
{

  public static void Main()
  {

    byte byte1 = 0x9a;  // binary 10011010, decimal 154
    byte byte2 = 0xdb;  // binary 11011011, decimal 219
    byte result;

    System.Console.WriteLine("byte1 = " + byte1);
    System.Console.WriteLine("byte2 = " + byte2);

    
    result = (byte) (byte1 & byte2);
    System.Console.WriteLine("byte1 & byte2 = " + result);

  }

}

The code above generates the following result.

Use bitwise AND to make a number even

using System; /* j a v a  2  s  . c om*/
 
class Example {  
  public static void Main() { 
    ushort num;  
    ushort i;     
 
    for(i = 1; i <= 10; i++) { 
      num = i; 
 
      Console.WriteLine("num: " + num); 
 
      num = (ushort) (num & 0xFFFE); // num & 1111 1110 
 
      Console.WriteLine("num after turning off bit zero: " 
                        +  num + "\n");  
    } 
  } 
}

The code above generates the following result.

Use bitwise AND to determine if a number is odd.

using System; //from  java  2s  .co  m
 
class Example {  
  public static void Main() { 
    ushort num;  
 
    num = 10; 
 
    if((num & 1) == 1) 
      Console.WriteLine("This won't display."); 
 
    num = 11; 
 
    if((num & 1) == 1) 
      Console.WriteLine(num + " is odd."); 
 
  } 
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Use bitwise OR to make a number odd.
Home » C# Tutorial » 
C# operators
Arithmetic Operators
Assignment Operator
Remainder operator
Increment operator and decrement operators
Logic operators
Logic operator shortcut
Relational operators
sizeof
Ternary operator(The ? Operator)
typeof
Bitwise Operators
bitwise AND
bitwise OR
bitwise NOT
bitwise exclusive OR
Shift Operators
Precedence of the C# Operators