mayap

ModifyBitAtGivenPosition

Apr 11th, 2014
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.23 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. namespace ModifyBitsAtPosition
  8. {
  9.     class Program
  10.     {
  11.         static void Main()
  12.         {
  13.             Console.WriteLine("n=");
  14.             int n = int.Parse(Console.ReadLine());
  15.             Console.WriteLine("p=");
  16.             int p = int.Parse(Console.ReadLine());
  17.             Console.WriteLine("v=");
  18.             int v = int.Parse(Console.ReadLine());
  19.  
  20.            
  21.             int nRightP = n >> p;
  22.             int bit = nRightP & 1;
  23.  
  24.             int mask;
  25.             int result;
  26.  
  27.             if (bit == 0 & v == 0)
  28.             {
  29.                 Console.WriteLine(n);
  30.             }
  31.             else if (bit == 0 && v == 1)
  32.             {
  33.                 mask = 1 << p;
  34.                 result = n | mask;
  35.                 Console.WriteLine(result);
  36.             }
  37.             else if (bit == 1 && v == 0)
  38.             {
  39.                 mask = ~(1 << p);
  40.                 result = n & mask;
  41.                 Console.WriteLine(result);
  42.  
  43.             }
  44.             else if (bit == 1 && v == 1)
  45.             {
  46.                 Console.WriteLine(n);
  47.             }
  48.            
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment