Advertisement
Siropo

exchangesBits

Nov 10th, 2012
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.32 KB | None | 0 0
  1. //Write a program that exchanges bits 3, 4 and 5 with bits 24, 25 and 26 of given 32-bit unsigned integer.
  2.  
  3. using System;
  4.  
  5. class exchangesBits
  6. {
  7.     static void Main()
  8.     {
  9.  
  10.         int n = 2063597567;
  11.         int mask = 0;
  12.         int nAndMask = 0;
  13.         int bit = 0;
  14.         int[] myArray = new int[3];
  15.         int replace = n;
  16.  
  17.         for (int i = 0; i < 3; i++)
  18.         {
  19.             int p = 24; // start position to get bits
  20.             p += i;     // position 24 25 26
  21.             mask = 1 << p;
  22.             nAndMask = n & mask;
  23.             bit = nAndMask >> p; // return bit on position
  24.             myArray[i] = bit; // create array whit bits
  25.         }
  26.  
  27.         for (int i = 0; i < 3; i++)
  28.         {
  29.             int p = 3; // start position to get bits
  30.             p += i; // position 3 4 5
  31.             mask = 1 << p;
  32.             nAndMask = n & mask;
  33.             bit = nAndMask >> p; // return bit on position
  34.             if (bit != myArray[i]) // if bit on position 3 4 5 not equal to position 24 25 26
  35.             {
  36.                 replace = replace ^ mask; // replace bit on this position whit bit on current array position
  37.             }
  38.         }
  39.         Console.WriteLine(Convert.ToString(n, 2).PadLeft(32, '0'));
  40.         Console.WriteLine(Convert.ToString(replace, 2).PadLeft(32, '0'));
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement