Advertisement
kuruku

PrintBitInGivenPosition2

Apr 16th, 2014
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.02 KB | None | 0 0
  1. using System;
  2.  
  3.  
  4.     //We are given a number n and a position p. Write a sequence of
  5.     //operations that prints the value of the bit on the position p in the
  6.     //number (0 or 1). Example: n=35, p=5 -> 1. Another example: n=35,
  7.     //p=6 -> 0.
  8.  
  9. class PrintBitInGivenPosition
  10. {
  11.     static void Main()
  12.     {
  13.         Console.Write("n = ");
  14.         int n = int.Parse(Console.ReadLine());
  15.         Console.Write("p = ");
  16.         int p = int.Parse(Console.ReadLine());
  17.         int mask = (int)Math.Pow(2, p);
  18.         string binaryMask = Convert.ToString(mask, 2);   //binary of n
  19.        
  20.         string binaryN = Convert.ToString(n, 2);   //binary of n
  21.         //Console.WriteLine(binaryMask);
  22.         //Console.WriteLine(binaryN);
  23.  
  24.         int position = mask & n;
  25.         //Console.WriteLine(position);
  26.         if (position == 0)
  27.         {
  28.             Console.WriteLine("Bit of position {0} = 0",p);
  29.         }
  30.         else
  31.         {
  32.             Console.WriteLine("Bit of position {0} = 1", p);
  33.  
  34.         }
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement