Advertisement
Guest User

ModifyBitAtPosition

a guest
Mar 15th, 2014
332
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.68 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. /*
  8.  * We are given an integer number n, a bit value v (v=0 or 1) and a position p.
  9.  * Write a sequence of operators (a few lines of C# code) that modifies n
  10.  * to hold the value v at the position p from the binary representation of n
  11.  * while preserving all other bits in n.
  12.  */
  13. class ModifyBitAtPos
  14. {
  15.     static void Main()
  16.     {
  17.         int haystack;
  18.         int position;
  19.         int setTo;
  20.  
  21.         Console.WriteLine("Please, enter unsigned integer:");
  22.         while (!int.TryParse(Console.ReadLine(), out haystack))
  23.         {
  24.             Console.WriteLine("Please, enter correct integer.");
  25.         }
  26.         Console.WriteLine("Please, set the bit position you are interested in:");
  27.         while (!int.TryParse(Console.ReadLine(), out position))
  28.         {
  29.             Console.WriteLine("Please, enter correct integer.");
  30.         }
  31.         Console.WriteLine("Provide the bit value you like to be set:");
  32.         while (!int.TryParse(Console.ReadLine(), out setTo) && (setTo != 0 || setTo != 1) )
  33.         {
  34.             Console.WriteLine("Please, enter correct integer.");
  35.         }
  36.         int mask = 1;
  37.        
  38.         bool boolResult = (haystack & (1 << position)) != 0;
  39.         //Console.WriteLine(boolResult);
  40.  
  41.         if ((setTo == 1 && boolResult) || (setTo == 0 && !boolResult))
  42.         {
  43.             Console.WriteLine(haystack);
  44.         }
  45.         else if ((setTo == 1 && !boolResult) || (setTo == 0 && boolResult))
  46.         {
  47.             Console.WriteLine(haystack ^ (mask << position));
  48.         }
  49.  
  50.         Console.ReadKey();
  51.  
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement