Advertisement
Masovski

[C# Basics][HW 3] 15. ExchangeBits

Mar 17th, 2014
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.08 KB | None | 0 0
  1. /* Description:
  2.  * Write a program that exchanges bits 3, 4 and 5 with bits 24, 25 and 26 of given 32-bit unsigned integer.
  3.  */
  4. using System;
  5.  
  6. class BitsExchange
  7. {
  8.     static void Main()
  9.     {
  10.  
  11.         while (true)
  12.         {
  13.                
  14.             Console.Write("Number: ");
  15.             uint number = uint.Parse(Console.ReadLine());
  16.          
  17.             // Set positions
  18.             int[] position1 = {  3,  4,  5};
  19.             int[] position2 = { 24, 25, 26 };
  20.             if (position1.Length != position2.Length)
  21.             {
  22.                 Console.WriteLine("The positions should've an equal length");
  23.                 return;
  24.             }
  25.  
  26.             for (int i = position1.Length - 1; i >= 0; i--) // position1.Length is 3 but arrays start from 0
  27.             {
  28.                 // Getting the first bit
  29.                 uint tempBit = number >> position1[i];
  30.                 tempBit = tempBit & 1;
  31.  
  32.                 // Getting the second bit
  33.                 uint secondTempBit = number >> position2[i];
  34.                 secondTempBit = secondTempBit & 1;
  35.  
  36.                 // Placing the first bit into the position of the second
  37.                 if (tempBit == 0)
  38.                 {
  39.                     int mask = ~(1 << position2[i]);
  40.                     number = number & (uint)mask;
  41.                 }
  42.                 else if (tempBit == 1)
  43.                 {
  44.                     int mask = 1 << position2[i];
  45.                     number = number | (uint)mask;
  46.                
  47.                 }
  48.                    
  49.                 // Placing the first bit into the position of the second
  50.                 if (secondTempBit == 0)
  51.                 {
  52.                     int mask = ~(1 << position1[i]);
  53.                     number = number & (uint)mask;
  54.                 }
  55.                 else if (secondTempBit == 1)
  56.                 {
  57.                     int mask = 1 << position1[i];
  58.                     number = number | (uint)mask;
  59.                    
  60.                 }
  61.  
  62.             }
  63.             Console.WriteLine(number);
  64.         }
  65.  
  66.     }
  67.        
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement