Advertisement
Fundamentalen

ModifyABitAtGivenPosition

Mar 14th, 2014
1,728
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.98 KB | None | 0 0
  1. using System;
  2.  
  3. class ModifyABitAtGivenPosition
  4. {
  5.     static void Main()
  6.     {
  7.         Console.Write("Enter your number: ");
  8.         int number = int.Parse(Console.ReadLine());
  9.         Console.Write("Check bit of position: ");
  10.         int position = int.Parse(Console.ReadLine());
  11.         Console.Write("Value of bit [0 or 1]: ");
  12.         int value = int.Parse(Console.ReadLine());
  13.  
  14.         Console.WriteLine(Convert.ToString(number, 2).PadLeft(16, '0'));
  15.  
  16.         if (value == 1)
  17.         {
  18.             int setOne = 1 << position;
  19.             int foundBitOne = number | setOne;
  20.             Console.WriteLine(Convert.ToString(foundBitOne, 2).PadLeft(16, '0'));
  21.             Console.WriteLine(foundBitOne);
  22.         }
  23.         else
  24.         {
  25.             int setZero = ~(1 << position);
  26.             int foundBitZero = number & setZero;
  27.             Console.WriteLine(Convert.ToString(foundBitZero, 2).PadLeft(16, '0'));
  28.             Console.WriteLine(foundBitZero);
  29.         }
  30.     }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement