Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- //We are given the number n, the value v (v = 0 or 1) and the position p.
- //write a sequence of operations that changes the value of n, so the bit on
- //the position p has the value of v. Example: n=35, p=5, v=0 -> n=3.
- //Another example: n=35, p=2, v=1 -> n=39.
- class ChangeGivenBitInGivenPosition
- {
- static void Main()
- {
- Console.Write("Number = ");
- int n = int.Parse(Console.ReadLine());
- Console.Write("Position of bit = ");
- int p = int.Parse(Console.ReadLine());
- Console.Write("Value of bit = ");
- int v = int.Parse(Console.ReadLine());
- int newNumber = 0;
- //string nBinary = Convert.ToString(n, 2).PadLeft(32, '0'); //binary of n
- //Console.WriteLine("n = {0}",nBinary);
- int pPow = (int)Math.Pow(2, p);
- //string pPowBinary = Convert.ToString(p, 2).PadLeft(32, '0'); //binary of p
- //Console.WriteLine("p = {0}", pPowBinary);
- if (v == 1)
- {
- newNumber = n | pPow;
- }
- else
- {
- int mask = ~(1 << p);
- newNumber = n & mask;
- }
- Console.WriteLine("New Number = " + newNumber);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement