Advertisement
VyaraG

ModifyABitAtGivenPosition

Nov 28th, 2014
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.13 KB | None | 0 0
  1. using System;
  2.  
  3. //We are given an integer number n, a bit value v (v=0 or 1) and a position p. Write a sequence of operators (a few lines of C# code) that modifies n to hold the value v at the position p from the binary representation of n while preserving all other bits in n.
  4.  
  5. class ModifyABitAtGivenPosition
  6. {
  7.     static void Main()
  8.     {
  9.         Console.Write("Enter a number: ");
  10.         int number = int.Parse(Console.ReadLine());
  11.         Console.Write("Enter a bit value (either '1', or '0'): ");
  12.         int bitValue = int.Parse(Console.ReadLine());
  13.         Console.Write ("Enter a number to indicate the position at which the bit is to be exchanged: ");
  14.         int position = int.Parse(Console.ReadLine());
  15.  
  16.         if (bitValue==0)
  17.         {
  18.             int mask = ~(1 << position);
  19.             int result = (mask & number);
  20.             Console.WriteLine(result);
  21.  
  22.         }
  23.         else if (bitValue==1)
  24.         {
  25.             int mask = 1 << position;
  26.             int result = number | mask;
  27.             Console.WriteLine(result);
  28.         }
  29.         else
  30.             Console.WriteLine("Incorrect value!");
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement