Advertisement
TzvetanIG

homework3Proplem16

Mar 15th, 2014
317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.92 KB | None | 0 0
  1. using System;
  2.  
  3. class BitsExchange
  4. {
  5.     static void Main()
  6.     {
  7.         Console.Write("n = ");
  8.         uint number = uint.Parse(Console.ReadLine());
  9.  
  10.         Console.Write("Start position of first sequence: ");
  11.         int p = int.Parse(Console.ReadLine());
  12.  
  13.         Console.Write("Start position of second sequence: ");
  14.         int q = int.Parse(Console.ReadLine());
  15.  
  16.         Console.Write("Lenght of sequences: ");
  17.         int k = int.Parse(Console.ReadLine());
  18.  
  19.         bool isOutOfRangeP = p < 0 || p + k - 1 > 31;
  20.         bool isOutOfRangeQ = q < 0 || q + k - 1 > 31;
  21.  
  22.         if (isOutOfRangeP || isOutOfRangeQ)
  23.         {
  24.             Console.WriteLine("out of range");
  25.             return;
  26.         }
  27.  
  28.         if ((p <= q && q <= p + k - 1) || (q <= p && p <= q + k - 1))
  29.         {
  30.             Console.WriteLine("overlapping");
  31.             return;
  32.         }
  33.  
  34.         uint result = number;
  35.  
  36.         for (byte i = 0; i < k; i++, p++, q++)
  37.         {
  38.             uint bit1 = GetABit(result, p);
  39.             uint bit2 = GetABit(result, q);
  40.             result = ModifyABit(result, p, bit2);
  41.             result = ModifyABit(result, q, bit1);
  42.         }
  43.         Console.WriteLine();
  44.         Console.WriteLine(Convert.ToString(number, 2));
  45.         Console.WriteLine(Convert.ToString(result, 2));
  46.         Console.WriteLine("result: " + result);
  47.     }
  48.  
  49.  
  50.     static uint GetABit(uint number, int position)
  51.     {
  52.         return (number >> position) % 2;
  53.     }
  54.  
  55.  
  56.     static uint ModifyABit(uint number, int ModifyPosition, uint newBitValue)
  57.     {
  58.         uint modifyNumber = number;
  59.  
  60.         if (newBitValue == 0)
  61.         {
  62.             uint mask = ~(1u << ModifyPosition);
  63.             modifyNumber = number & mask;
  64.         }
  65.         else if (newBitValue == 1)
  66.         {
  67.             uint mask = 1u << ModifyPosition;
  68.             modifyNumber = number | mask;
  69.         }
  70.  
  71.         return modifyNumber;
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement