Advertisement
kuruku

PrintBitInGivenPosition

Apr 16th, 2014
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.88 KB | None | 0 0
  1. using System;
  2.  
  3. //Using bitwise operators, write an expression for finding the value of the bit #3 of a given unsigned integer.
  4. //The bits are counted from right to left, starting from bit #0. The result of the expression should be either 1 or 0. Examples:
  5.  
  6. class PrintBitInGivenPosition
  7. {
  8.     static void Main()
  9.     {
  10.         Console.Write("n = ");
  11.         int n = int.Parse(Console.ReadLine());
  12.         Console.WriteLine("p = 3");
  13.         int p = 3;
  14.         int mask = (int)Math.Pow(2, p);
  15.         string binaryMask = Convert.ToString(mask, 2);   //binary of n
  16.  
  17.         string binaryN = Convert.ToString(n, 2);   //binary of n
  18.  
  19.         int position = mask & n;
  20.         if (position == 0)
  21.         {
  22.             Console.WriteLine("Bit of position {0} = 0", p);
  23.         }
  24.         else
  25.         {
  26.             Console.WriteLine("Bit of position {0} = 1", p);
  27.  
  28.         }
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement