Advertisement
stak441

operators - task 14

Nov 15th, 2012
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.07 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace _14.exchangeGivenBits
  7. {
  8.     class exchangeBits
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             uint givenInt = 70345;   //random 32 bit number
  13.             Console.WriteLine("given integer is: {0}", Convert.ToString(givenInt, 2).PadLeft(32, '0'));  //display it as binary
  14.             byte positionCount = 3;     //number of adjacent positions that will be subject to modification
  15.             byte firstGroupStart = 4;   //the first group of bits is defined by starting position (k) and the positionCount number
  16.             byte secondGroupStart = 10;   //the second group of bits is defined by starting position (q) and the positionCount number
  17.             uint mask = (uint)(1 * (1 - Math.Pow(2, positionCount)) / (1 - 2));  //this is a modified sum of geometric progression
  18.  
  19.             Console.WriteLine("The mask is {0}", Convert.ToString(mask, 2));    //example: 3 desired positions will give us number 7 (or 111)
  20.  
  21.                 uint firstBits = (mask << firstGroupStart) & givenInt;         //gets the bits of the first group
  22.                 firstBits = firstBits << secondGroupStart;                    //moves them q positions to the left
  23.                 uint secondBits = (mask << secondGroupStart) & givenInt;       //analogically for the second group  
  24.                 secondBits = secondBits >> firstGroupStart;
  25.  
  26.                 givenInt = (~(mask << firstGroupStart)) & givenInt;           //bits of the first group will become 0
  27.                 uint modifiedResult = givenInt | secondBits;               //extracted bits from second group replace bits in first group
  28.                
  29.                 givenInt = (~(mask << secondGroupStart)) & givenInt;          //analogically for the second group
  30.                 modifiedResult = givenInt | firstBits;
  31.  
  32.                 Console.WriteLine("Result: {0}", Convert.ToString(modifiedResult, 2).PadLeft(32, '0'));     //final result
  33.                 Console.WriteLine(modifiedResult);
  34.  
  35.  
  36.         }
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement