Advertisement
stkirov

12.BitModfier

Oct 15th, 2012
556
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.94 KB | None | 0 0
  1. //We are given integer number n, value v (v=0 or 1) and a position p. Write a sequence of operators
  2. //that modifies n to hold the value v at the position p from the binary representation of n.
  3. //  Example: n = 5 (00000101), p=3, v=1  13 (00001101)
  4. //  n = 5 (00000101), p=2, v=0  1 (00000001)
  5. using System;
  6. using System.Collections.Generic;
  7.  
  8. class Program
  9. {
  10.     static void Main()
  11.     {
  12.         int n = int.Parse(Console.ReadLine());
  13.         int p = int.Parse(Console.ReadLine());
  14.         int v = int.Parse(Console.ReadLine());
  15.         int mask = 1<<p;
  16.         int maskIf = (mask&n)!=0 ? 1 : 0; //determine the bit in position p
  17.  
  18.         Console.WriteLine("Before: {0}",Convert.ToString(n, 2).PadLeft(32, '0'));
  19.         if (maskIf==0)
  20.         {
  21.             n |= (1 << p);
  22.         }
  23.         else
  24.         {
  25.             n &= ~(1 << p);
  26.         }
  27.         Console.WriteLine("After: {0}",Convert.ToString(n, 2).PadLeft(32, '0'));
  28.  
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement