Advertisement
dimipan80

3.ExchangesBitsIn32Integer_AdvancedTask

Apr 5th, 2014
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.06 KB | None | 0 0
  1. using System;
  2.  
  3. class BitsExchange_AdvancedTask
  4. {
  5.     static void Main ()
  6.     {
  7.         checked
  8.         {
  9.             Console.Write("Please, enter a whole non-negative Integer number N = ");
  10.             string numberStr = Console.ReadLine();
  11.             int numberN = int.Parse(numberStr);
  12.             Console.Write("Enter a whole number for a bit position in the range [0...30], P = ");
  13.             numberStr = Console.ReadLine();
  14.             int bitPositionP = int.Parse(numberStr);
  15.             Console.Write("Enter other whole number for a bit position in the range [0...30], Q = ");
  16.             numberStr = Console.ReadLine();
  17.             int bitPositionQ = int.Parse(numberStr);
  18.             Console.Write("Enter a whole number for a count of bit positions in the range [2...31], K = ");
  19.             numberStr = Console.ReadLine();
  20.             int countBitsK = int.Parse(numberStr);
  21.             if ((bitPositionP + countBitsK) > 32 || (bitPositionQ + countBitsK) > 32)
  22.             {
  23.                 Console.WriteLine("Error - Invalid Input !!!");
  24.                 Console.ReadLine();
  25.                 return;
  26.             }
  27.  
  28.             // Get bits from the number
  29.             int firstSequenceBits = 0;
  30.             int secondSequenceBits = 0;
  31.             for (int i = 0; i < countBitsK; i++)
  32.             {
  33.                 if ((numberN & (1 << (bitPositionP + i))) != 0)
  34.                 {
  35.                     firstSequenceBits |= (1 << i);
  36.                 }
  37.                 numberN &= ~(1 << (bitPositionP + i));
  38.  
  39.                 if ((numberN & (1 << (bitPositionQ + i))) != 0)
  40.                 {
  41.                     secondSequenceBits |= (1 << i);
  42.                 }
  43.                 numberN &= ~(1 << (bitPositionQ + i));
  44.             }
  45.  
  46.             // Exchange the bits            
  47.             numberN |= secondSequenceBits << bitPositionP;
  48.             numberN |= firstSequenceBits << bitPositionQ;
  49.  
  50.             // Print result
  51.             Console.WriteLine("The result number is NEW NUMBER = {0} !", numberN);
  52.             Console.ReadLine();
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement