lmarkov

Modify Number Bits

Nov 29th, 2012
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.20 KB | None | 0 0
  1. /*
  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)
  4.     n = 5 (00000101), p=2, v=0  1 (00000001)
  5. */
  6.  
  7. using System;
  8.  
  9. class ModifyNumberBits
  10. {
  11.     static void Main()
  12.     {
  13.         int numberN, valueV, positionP, numberMask, modifiedNumber;
  14.         string errorInvalidInt = "Invalid input! Please enter number between " + int.MinValue + " and " + int.MaxValue + "!\n";
  15.  
  16.         Console.WriteLine("Enter integer number: ");
  17.         if (int.TryParse(Console.ReadLine(), out numberN) && numberN >= int.MinValue && numberN <= int.MaxValue)
  18.         {
  19.             Console.WriteLine("Binary code of your number {0}  is: {1}", numberN, Convert.ToString(numberN, 2).PadLeft(32, '0'));
  20.             Console.WriteLine("Enter bit position you want to modify (count from 0): ");
  21.             if (int.TryParse(Console.ReadLine(), out positionP) && positionP >= int.MinValue && positionP <= int.MaxValue)
  22.             {
  23.                 Console.WriteLine("Enter value V (0 or 1): ");
  24.                 while (!(int.TryParse(Console.ReadLine(), out valueV) && (valueV == 0 || valueV == 1)))
  25.                 {
  26.                     Console.WriteLine("Enter value V (0 or 1): ");
  27.                 }
  28.                 if (valueV == 0)
  29.                 {
  30.                     numberMask = ~(1 << positionP);
  31.                     modifiedNumber = numberN & numberMask;
  32.                 }
  33.                 else
  34.                 {
  35.                     numberMask = 1 << positionP;
  36.                     modifiedNumber = numberN | numberMask;
  37.                 }
  38.  
  39.                 Console.WriteLine("{0}: \t{1}\n{2}: \t{3}\n", numberN, Convert.ToString(numberN, 2).PadLeft(32, '0'), modifiedNumber, Convert.ToString(modifiedNumber, 2).PadLeft(32, '0'));
  40.                 Main();
  41.             }
  42.             else
  43.             {
  44.                 Console.WriteLine(errorInvalidInt);
  45.                 Main();
  46.             }            
  47.         }
  48.         else
  49.         {
  50.             Console.WriteLine(errorInvalidInt);
  51.             Main();
  52.         }
  53.        
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment