coasterka

#3ModifyBiAtCurrPosition

Mar 13th, 2014
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.54 KB | None | 0 0
  1. static void Main()
  2.         {
  3.             Console.WriteLine("Enter a number to change a current bit of its binary code.");
  4.             int n = int.Parse(Console.ReadLine());
  5.             Console.WriteLine("Which bit position you'd like to change?");
  6.             int p = int.Parse(Console.ReadLine());
  7.             Console.WriteLine("What value would you like the bit at pos {0} to hold?\nChoose between 0 and 1", p);
  8.             int v = int.Parse(Console.ReadLine());
  9.             Console.WriteLine("Number in binary: {0}", Convert.ToString(n, 2).PadLeft(16, '0'));
  10.             switch (v)
  11.             {
  12.                 case 0:
  13.                     {
  14.                         int mask = ~(1 << p);
  15.                         int result = mask & n;
  16.                         Console.WriteLine("Result in decimal: {0}", result);
  17.                         Console.WriteLine("Result in binary: {0}", Convert.ToString(result, 2).PadLeft(16, '0'));
  18.                         break;
  19.                     }
  20.                 case 1:
  21.                     {
  22.                         int mask = 1 << p;
  23.                         int result = mask | n;
  24.                         Console.WriteLine("Result in decimal: {0}", result);
  25.                         Console.WriteLine("Result in binary: {0}", Convert.ToString(result, 2).PadLeft(16, '0'));
  26.                         break;
  27.                     }
  28.                 default:
  29.                     {
  30.                         Console.WriteLine("Wrong input!");
  31.                         break;
  32.                     }
  33.             }
  34.         }
Advertisement
Add Comment
Please, Sign In to add comment