AnitaN

03.OperatorsExpressionsStatements/14.ModifyBitGivenPosition

Mar 20th, 2014
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.51 KB | None | 0 0
  1. //Problem 14.   Modify a Bit at Given Position
  2. //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)
  3. //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. using System;
  6.  
  7. class ModifyBitGivenPosition
  8. {
  9.     static void Main()
  10.     {
  11.         Console.Write("Please, enter some number:");
  12.         int nNumber = int.Parse(Console.ReadLine());
  13.         Console.Write("Please, enter bit position p to modify:");
  14.         byte position = byte.Parse(Console.ReadLine());
  15.         Console.Write("Please, enter bit value 0 or 1:");
  16.         byte bitValue = byte.Parse(Console.ReadLine());
  17.         Console.WriteLine("INPUT: " + Convert.ToString(nNumber, 2).PadLeft(16, '0'));
  18.         if (bitValue == 0)
  19.         {
  20.             // set bit at position p to 0
  21.             int mask = ~(1 << position);
  22.             int result = nNumber & mask;
  23.             Console.WriteLine("RESULT:" + Convert.ToString(result, 2).PadLeft(16, '0'));
  24.             Console.WriteLine(result);
  25.         }
  26.         else if (bitValue == 1)
  27.         {
  28.             // set bit at position p to 1
  29.             int mask = 1 << position;
  30.             int result = nNumber | mask;
  31.             Console.WriteLine("RESULT:" + Convert.ToString(result, 2).PadLeft(16, '0'));
  32.             Console.WriteLine(result);
  33.         }
  34.         else
  35.         {
  36.             Console.WriteLine("Wrong input! Try Again.");
  37.         }
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment