Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- //We are given a number n and a position p. Write a sequence of
- //operations that prints the value of the bit on the position p in the
- //number (0 or 1). Example: n=35, p=5 -> 1. Another example: n=35,
- //p=6 -> 0.
- class PrintBitInGivenPosition
- {
- static void Main()
- {
- Console.Write("n = ");
- int n = int.Parse(Console.ReadLine());
- Console.Write("p = ");
- int p = int.Parse(Console.ReadLine());
- int mask = (int)Math.Pow(2, p);
- string binaryMask = Convert.ToString(mask, 2); //binary of n
- string binaryN = Convert.ToString(n, 2); //binary of n
- //Console.WriteLine(binaryMask);
- //Console.WriteLine(binaryN);
- int position = mask & n;
- //Console.WriteLine(position);
- if (position == 0)
- {
- Console.WriteLine("Bit of position {0} = 0",p);
- }
- else
- {
- Console.WriteLine("Bit of position {0} = 1", p);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement