Razhagal

ExchangeBits

Mar 15th, 2014
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.31 KB | None | 0 0
  1. using System;
  2. class BitExchangeAdvanced
  3. {
  4.     static void Main()
  5.     {
  6.         long num = long.Parse(Console.ReadLine());
  7.         int firstPos = int.Parse(Console.ReadLine());
  8.         int secondPos = int.Parse(Console.ReadLine());
  9.         int k = int.Parse(Console.ReadLine()); //number of positions that need to be exchanged
  10.         int counter = 0;
  11.         long bitOnFirstPos;
  12.         long bitOnSecondPos;
  13.  
  14.         if (firstPos + k > 31 || secondPos + k > 31)
  15.         {
  16.             Console.WriteLine("Out of range");
  17.             return;
  18.         }
  19.         else if (k > firstPos && k > secondPos)
  20.         {
  21.             Console.WriteLine("Overlapping");
  22.             return;
  23.         }
  24.  
  25.         while (counter < k)
  26.         {
  27.             bitOnFirstPos = (num >> firstPos) & 1;
  28.             bitOnSecondPos = (num >> secondPos) & 1;
  29.  
  30.             if (bitOnFirstPos == 1 && bitOnSecondPos == 0)
  31.             {
  32.                 num = (bitOnFirstPos << secondPos) | num;
  33.                 num = ~(1 << firstPos) & num;
  34.             }
  35.             else if (bitOnFirstPos == 0 && bitOnSecondPos == 1)
  36.             {
  37.                 num = ~(1 << secondPos) & num;
  38.                 num = (bitOnSecondPos << firstPos) | num;
  39.             }
  40.  
  41.             firstPos++;
  42.             secondPos++;
  43.             counter++;
  44.         }
  45.  
  46.         Console.WriteLine(num);
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment