Advertisement
soxa

HoldValuePositionBinary

Nov 7th, 2013
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.05 KB | None | 0 0
  1. using System;
  2. // We are given integer number n, value v (v=0 or 1) and a position p. Write a sequence of operators 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); n = 5 (00000101), p=2, v=0 --> 1 (00000001)
  4.  
  5. class HoldValuePositionBinary
  6. {
  7.     static void Main()
  8.     {
  9.         Console.Write("Enter n = ");
  10.         int n = int.Parse(Console.ReadLine());  // number
  11.         Console.Write("Enter v = ");
  12.         int v = int.Parse(Console.ReadLine());  // v = 1 or 0
  13.         Console.Write("Enter p = ");
  14.         int p = int.Parse(Console.ReadLine());  // position
  15.         int bit = 0;
  16.         int mask = 1;
  17.  
  18.         bit = mask << p;
  19.         bit = (n & bit) >> p;
  20.         if (bit != v) // if (bit != v)
  21.         {
  22.             bit = mask << p;
  23.             n ^= bit;
  24.             Console.WriteLine(n);
  25.         }
  26.         else // if (bit = v)
  27.         {
  28.             bit = mask << p;
  29.             n |= bit;
  30.             Console.WriteLine(n);
  31.         }
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement