Advertisement
kuruku

ChangeGivenBitInGivenPosition

Apr 16th, 2014
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.22 KB | None | 0 0
  1. using System;
  2.  
  3. //We are given the number n, the value v (v = 0 or 1) and the position p.
  4. //write a sequence of operations that changes the value of n, so the bit on
  5. //the position p has the value of v. Example: n=35, p=5, v=0 -> n=3.
  6. //Another example: n=35, p=2, v=1 -> n=39.
  7.  
  8. class ChangeGivenBitInGivenPosition
  9. {
  10.     static void Main()
  11.     {
  12.         Console.Write("Number = ");
  13.         int n = int.Parse(Console.ReadLine());
  14.         Console.Write("Position of bit = ");
  15.         int p = int.Parse(Console.ReadLine());
  16.         Console.Write("Value of bit = ");
  17.         int v = int.Parse(Console.ReadLine());
  18.  
  19.         int newNumber = 0;
  20.         //string nBinary = Convert.ToString(n, 2).PadLeft(32, '0');   //binary of n
  21.         //Console.WriteLine("n = {0}",nBinary);
  22.         int pPow = (int)Math.Pow(2, p);
  23.         //string pPowBinary = Convert.ToString(p, 2).PadLeft(32, '0');   //binary of p    
  24.         //Console.WriteLine("p = {0}", pPowBinary);
  25.    
  26.  
  27.         if (v == 1)
  28.         {
  29.             newNumber = n | pPow;
  30.         }
  31.         else
  32.         {
  33.             int  mask = ~(1 << p);
  34.             newNumber = n & mask;
  35.  
  36.         }
  37.         Console.WriteLine("New Number = " + newNumber);
  38.  
  39.        
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement