BorisSimeonov

ModifyABitAtGivenPosition

Nov 10th, 2014
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.04 KB | None | 0 0
  1. using System;
  2.  
  3. class ModifyABitAtGivenPosition
  4. {
  5.     static void Main()
  6.     {
  7.         Console.WriteLine("Enter integer number: ");
  8.         int num = int.Parse(Console.ReadLine());
  9.         Console.WriteLine("Enter bit value: ");
  10.         int value = new int();
  11.         for (int cnt = 0; cnt < 1; cnt++)
  12.         {
  13.             value = int.Parse(Console.ReadLine());
  14.             if (value < 0 && value > 1)
  15.             {
  16.                 Console.WriteLine("Invalid Input (only 1 and 0 are allowed). Try Again.");
  17.                 cnt--;
  18.             }
  19.         }
  20.         Console.WriteLine("Enter bit position [0-n]: ");
  21.         int position = int.Parse(Console.ReadLine());
  22.         //-------------------------
  23.         bool checkBitValue = ((num >> position) & 1) == 1;
  24.         if (checkBitValue && value == 0)
  25.         {
  26.                 num -= (1 << position);
  27.         }
  28.         else
  29.         {
  30.             if (value == 1)
  31.             {
  32.                 num += (1 << position);
  33.             }
  34.         }
  35.         Console.WriteLine(num);
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment