Advertisement
sylviapsh

Exchange a Bit At certain Position In Integer Number

Dec 28th, 2012
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.28 KB | None | 0 0
  1. using System;
  2. class ExchangeBitAtPositionInIntNum
  3. {
  4.   static void Main()
  5.   {
  6.     //We are given integer number n, value v (v=0 or 1) and a position p. Write a sequence of operators that modifies n to hold the value v at the position p from the binary representation of n.
  7.     //Example: n = 5 (00000101), p=3, v=1 =>13 (00001101)
  8.     // n = 5 (00000101), p=2, v=0 => 1 (00000001)
  9.  
  10.  
  11.     Console.Write("Enter an integer number:");
  12.     int numberToModify = int.Parse(Console.ReadLine());
  13.     Console.Write("Enter a position to modify (0 to 31):");
  14.     int positionToModify = int.Parse(Console.ReadLine());
  15.     Console.Write("Enter a value to change (0 or 1):");
  16.     int valueToModify = int.Parse(Console.ReadLine());
  17.  
  18.     int modifiedNumber;
  19.  
  20.     if (valueToModify == 0)
  21.       modifiedNumber = (~(1 << positionToModify) & numberToModify);
  22.     else
  23.       modifiedNumber = ((1 << positionToModify) | numberToModify);
  24.  
  25.     Console.WriteLine("The number to modify is: {0}", Convert.ToString(numberToModify,2).PadLeft(32, '0'));
  26.     Console.WriteLine("The position to modify is: {0}", positionToModify);
  27.     Console.WriteLine("The value to modify with is: {0}", valueToModify);
  28.     Console.WriteLine("The modified number is: {0}", Convert.ToString(modifiedNumber, 2).PadLeft(32, '0'));
  29.   }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement