Advertisement
Asinka

16. ChangePosition-of-Bytes-P-Q

Oct 11th, 2012
439
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.74 KB | None | 0 0
  1. using System;
  2.  
  3.  
  4. class ChangePositionOfBytesPQ
  5. {
  6.     static void Main()
  7.     {
  8.         Console.Write("Enter positive number here: \nn = ");
  9.         int n = int.Parse(Console.ReadLine());
  10.         Console.Write("Enter position of bit to start: \np = ");
  11.         int p = int.Parse(Console.ReadLine());
  12.         Console.Write("Enter posiotion of bit to end: \nq = ");
  13.         int q = int.Parse(Console.ReadLine());
  14.         Console.Write("Haw many bits you wont to exchange: \nk = ");
  15.         int k = int.Parse(Console.ReadLine());
  16.         k = k + 1;
  17.  
  18.         for (int i = p, j = q; i < p + k - 1; i++, j++) //bits of position {p, p+1, …, p+k-1) and {q, q+1, …, q+k-1}
  19.         {    
  20.            
  21.             //chacking which bits stay of this positions - 0 or 1
  22.             int mask1 = 1 << i;
  23.             int mask2 = 1 << j;
  24.             int bit1 = (n & mask1);
  25.             int bit2 = (n & mask2);
  26.  
  27.             //bit of position {p, p+1, …, p+k-1) goes to bit of position {q, q+1, …, q+k-1}
  28.             if (bit1 == 0)
  29.             {
  30.                 int replacer = 1 << j;
  31.                 n = (n & ~replacer);
  32.             }
  33.             else
  34.             {
  35.                 int replacer = 1 << j;
  36.                 n = (n | replacer);
  37.             }
  38.  
  39.             //bit of position {q, q+1, …, q+k-1} goes to bit of position {p, p+1, …, p+k-1)
  40.             if (bit2 == 0)
  41.             {
  42.                 int replacer = 1 << i;
  43.                 n = (n & ~replacer);
  44.             }
  45.             else
  46.             {
  47.                 int replacer = 1 << i;
  48.                 n = (n | replacer);
  49.             }
  50.         }
  51.  
  52.  
  53.         Console.WriteLine("The number after bit changes (p, p+1, ... , p+k-1 <=> q, q+1, ... , q+k-1) is: \n{0}", n);
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement