Advertisement
v_staykov

ExchangeBits

Nov 14th, 2012
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.29 KB | None | 0 0
  1. using System;
  2.  
  3. class ExchangeBits
  4. {
  5.     static void Main()
  6.     {
  7.         Console.WriteLine("This program exchanges bits 3, 4 and 5 with bits 24, 25 and 26 of given\n32-bit unsigned integer.\n");
  8.         Console.Write("Please insert a positive integer number: ");
  9.         uint controlNumber = uint.Parse(Console.ReadLine());
  10.         uint resultNumber = controlNumber;
  11.         byte firstBitPosition = 3;
  12.         byte secondBitPosition = 24;
  13.        
  14.         for (byte i = 0; i < 3; i++, firstBitPosition++, secondBitPosition++)
  15.         {
  16.             uint secondTempVariable;
  17.             uint firstTempVariable;
  18.             uint firstBit;
  19.             uint secondBit;
  20.             uint mask = 1u;
  21.  
  22.             //Finding the value of the bit on position firstBitPosition (3,4,5)
  23.             mask <<= firstBitPosition;
  24.             firstBit = (mask & controlNumber);
  25.             firstBit >>= firstBitPosition;
  26.  
  27.             //Finding the value of the bit on position secondBitPosition (24,25,26)
  28.             mask = (1u << secondBitPosition);
  29.             secondBit = (mask & controlNumber);
  30.             secondBit >>= secondBitPosition;
  31.  
  32.             //Setting the value of bit firstBitPosition to position secondBitPosition
  33.             if (firstBit == 1)
  34.             {
  35.                 mask = 1u << secondBitPosition;
  36.                 secondTempVariable = resultNumber | mask;
  37.             }
  38.             else
  39.             {
  40.                 mask = ~(1u << secondBitPosition);
  41.                 secondTempVariable = resultNumber & mask;
  42.             }
  43.             firstTempVariable = secondTempVariable;
  44.  
  45.             //Setting value of bit secondBitPosition to position firstBitPosition
  46.             if (secondBit == 1)
  47.             {
  48.                 mask = 1u << firstBitPosition;
  49.                 resultNumber = (firstTempVariable | mask);
  50.             }
  51.             else
  52.             {
  53.                 mask = ~(1u << firstBitPosition);
  54.                 resultNumber = firstTempVariable & mask;
  55.             }
  56.  
  57.  
  58.         }
  59.         Console.WriteLine("\nThe new number is {0}.\n", resultNumber);
  60.         Console.WriteLine(controlNumber + " - " + Convert.ToString(controlNumber, 2).PadLeft(32, '0'));
  61.         Console.WriteLine(resultNumber + "-" + Convert.ToString(resultNumber, 2).PadLeft(32, '0'));
  62.     }
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement