svetlozar_kirkov

Change Bit At Position (Exercise)

Sep 27th, 2014
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.19 KB | None | 0 0
  1. using System;
  2.  
  3. namespace ConsoleTest
  4. {
  5.     class ConsoleTest
  6.     {
  7.         static void Main()
  8.         {
  9.             Console.Title = "Bit Operations Exercise";
  10.             int n = int.Parse(Console.ReadLine());
  11.             byte v = byte.Parse(Console.ReadLine());
  12.             int p = int.Parse(Console.ReadLine());
  13.             string num = Convert.ToString(n,2).PadLeft(8,'0');
  14.             Console.WriteLine(n+" in binary: " + num);
  15.             char bitAtPos = num[num.Length-p-1];
  16.             Console.WriteLine("bit at position "+ p +" --> " + bitAtPos);
  17.             if (int.Parse(bitAtPos.ToString()) == (int)v)
  18.             {
  19.                 Console.WriteLine(n + " (after its bit at position " + p + " was changed to " + v + ") is the same number --> " + n);
  20.             }
  21.             else
  22.             {
  23.                 int mask = 1 << p;
  24.                 int finalNum = n ^ mask;
  25.                 Console.WriteLine(n + " (after its bit at position " + p + " was changed to " + v + ") is different number --> " + finalNum);
  26.                 Console.WriteLine(finalNum + " in binary: " + Convert.ToString(finalNum, 2).PadLeft(8, '0'));
  27.             }
  28.            
  29.            
  30.         }
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment