Advertisement
Klaxon

[C# Operators] Sequence of Operators

Jul 9th, 2013
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.38 KB | None | 0 0
  1. // We are given integer number n, value v (v=0 or 1) and a position p.
  2. // 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)
  4. // n = 5 (00000101), p=2, v=0 --> 1 (00000001)
  5.  
  6. using System;
  7.  
  8. class SequenceOfOperators
  9. {
  10.     static void Main()
  11.     {
  12.         // Declaring needed variables
  13.         int number;
  14.         int value;
  15.         int position;
  16.  
  17.         // Get the number
  18.         Console.Write("Enter the number: ");
  19.         number = int.Parse(Console.ReadLine());
  20.  
  21.         // Get the value
  22.         Console.Write("Enter the value (1 or 0): ");
  23.         value = int.Parse(Console.ReadLine());
  24.  
  25.         // Get the position
  26.         Console.Write("Enter the position: ");
  27.         position = int.Parse(Console.ReadLine());
  28.  
  29.         // If the value is zero..
  30.         if (value == 0)
  31.         {
  32.             int mask = ~(position << 1);
  33.             int result = number & mask;
  34.             Console.WriteLine(result);
  35.         }
  36.        
  37.         // If the value is one..
  38.         else if (value == 1)
  39.         {
  40.             int mask = 1 << position;
  41.             int result = number | mask;
  42.             Console.WriteLine(result);
  43.         }
  44.         else
  45.         {
  46.             Console.WriteLine(@"Try to enter 1 or 0 at the ""value"".");
  47.         }
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement